首页 > 解决方案 > 编辑字符串而不更改非字母字符

问题描述

我需要制作一个像这样编辑命令行参数的程序:

  1. 将每个单词的第一个字母移动到单词的末尾,并将其变为小写
  2. 检查原始的第一个是否较低/较高并使新的第一个相同
  3. 将“o”添加到长度 < 3 的每个单词,并将“an”添加到其他单词
  4. 每个非 isalpha 字符保持不变
  5. 当有空格或 nonisalpha char 时,单词被认为是分开的

我有一些代码,但我的问题是我不知道如何在不修改它们的情况下保留字符串上的非 isalpha 字符。这是代码:

/*Example:
 
I *REALLY* like Yale's course-selection procedures.

to

Ian *EALLYro* ikelo Aleyo'san ourseco-electionso rocedurespo.
*/

int main(int argc, char *argv[])
{
    if(argc < 2)
    {
        printf("\nNot enough arguments! Press any key to exit.\n");
        system("pause");
        exit(0);
    }

    // copies the arguments to a string
    char src[100] = {0};
    for(int i = 1; i <= argc-1; i++)
    {
        strcat(src, argv[i]);
        strcat(src, " ");
    }
    printf("\nInput is:\n%s\n", src);


    // divides the main string in substrings when there is a space
    int k = 0, j = 0, m = 0, pos[50];
    char ans[100][100] = {0};

    
    // saves the position of the nonalpha characters
    for(int i = 0; i <= strlen(src); i++)
    {
        if(isalpha(src[i]) == 0 && isspace(src[i]) == 0)
        {
            pos[m] = i;
            m++;
        }
    }

    for(int i = 0; i <= strlen(src); i++)
    {
        if(src[i] == ' ' || src[i] == '\0' || isalpha(src[i]) == 0)
        {
            ans[k][j] = '\0';
            k++;       //for next word
            j = 0;    //for next word, init index to 0
        }
        else
        {
            ans[k][j] = src[i];
            j++;
        }
    }

    printf("\nOutput is: \n");
    for(int i = 0; i < k; i++)
    {
        processword(ans[i]);   // edits the words
        printf("%s ", ans[i]);

    }


    printf("\n\n");
    system("pause");
    return 0;
}

这就是我编辑单词的方式:

char* processword(char* word)
{
    if(strlen(word) == 0)
    {
        return NULL;
    }

    char first = word[0];                   // saves first letter
    for (int i = 0; i <= strlen(word); i++) // moves everything back one space
    {
       word[i-1] = word[i];
    }

    word[strlen(word)] = tolower(first); // moves first to end

    if (isupper(first) > 0)             // checks if the original first was uppercase, to make the new first the same
    {
        word[0] = toupper(word[0]);
    }

    // ads the suffix
    if(strlen(word) <= 3)
    {
        strcat(word, "an");
    }
    else
    {
        strcat(word, "o");
    }
    return word;
}

标签: cstringcommand-line

解决方案


推荐阅读