在C中输入和反转多个字符串?

时间:2018-11-22 08:48:18

标签: c arrays input

第一次在此论坛上发帖,但不是第一次浏览它!很有帮助的话题,现在我觉得该是时候寻求帮助了,因此在此先感谢那些可以帮助我的人。

我有以下几行代码:输入时,它们会颠倒单词的顺序。

即 输入:您好,我是蝙蝠侠 输出:蝙蝠侠在我身边

现在我希望允许用户输入多个字符串,即“ Hello there is Batman”; ''你好,世界'' ;等等。理想情况下,将这些输入用半角分隔,并用半角解析。

代码:

#include <stdio.h>

/* function prototype for utility function to
reverse a string from begin to end */
/*Function to reverse words*/
void reverseWords(char* s)
{
    char* word_begin = NULL;
    char* temp = s; /* temp is for word boundry */

    /*STEP 1 of the above algorithm */
    while (*temp) {
        /*This condition is to make sure that the string start with
        valid character (not space) only*/
        if ((word_begin == NULL) && (*temp != ' ')) {
            word_begin = temp;
        }
        if (word_begin && ((*(temp + 1) == ' ') || (*(temp + 1) == '\0'))) {
            reverse(word_begin, temp);
            word_begin = NULL;
        }
        temp++;
    } /* End of while */

    /*STEP 2 of the above algorithm */
    reverse(s, temp - 1);
}


/* UTILITY FUNCTIONS */
/*Function to reverse any sequence starting with pointer
begin and ending with pointer end */
void reverse(char* begin, char* end)
{
    char temp;
    while (begin < end) {
        temp = *begin;
        *begin++ = *end;
        *end-- = temp;
    }
}

/*
int main( void )
{
    int i, n;
    printf("Enter no of strings:");
    scanf("%i", &n);
    char **str = (char **) malloc( n* sizeof(char*));

    for (i = 0; i < n; i++) {
        str[i] = (char*) malloc(100);
        fgets(str[i],100,stdin);
    }

    for (i = 0; i < n; i++) {
        printf("%s", str[i]);
    }

    for (i = 0;  i < n; i++) {
        free(str[i]);
    }
    free(str);
    return 0;
}
*/

/* Driver function to test above functions */
int main()
{

        char str[50];
        char* temp = str;
        printf("Enter a string : ");
        gets(str);
        reverseWords(str);
        printf("%s", str);
        return(0);

}

1 个答案:

答案 0 :(得分:0)

使用其中一条注释中提到的strtok,您可以这样做:

void reverseSentence(char* sent){
    char *argv[25]; // This assumes you have a max of 25 words
    int  argc = 0;
    char* token = strtok(sent, " ");
    while (token != NULL) {
        argv[argc] = malloc(100); // This assumes each word is 99 characters at most
        strcpy(argv[argc++], token);
        token = strtok(NULL, " ");
    }

    for(int z = argc-1; z>=0; z--)
        fprintf(stdout, "%s ", argv[z]);

    fprintf(stdout, "\n");

}

警告!我没有测试代码,所以那里可能有一些错误……例如缺少半冒号,变量名不匹配等……