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

标签 c arrays input

第一次在这个论坛发帖,但不是第一次浏览这个论坛!非常有用的帖子,现在我觉得是时候寻求一些帮助了,所以提前感谢那些可以帮助我的人。

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

即 输入:你好,我是 bat 侠 输出: bat 侠我在吗你好

现在我想允许用户能够输入多个字符串,即“你好,我是 bat 侠”; '' Hello World '' ;等等。理想情况下,输入时用分号分隔并用分号进行解析。

代码:

#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);

}

最佳答案

使用 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");

}

警告!我没有测试代码,所以你可能有一些错误...比如缺少分号、变量名称不匹配等等...

关于c - 在C中输入和反转多个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53426980/

相关文章:

c - 如何直接访问显卡的输出?

创建和销毁线程

php - 改进 PHP 数组以在 AJAX 上使用

assembly - 如何检查 x86 程序集中的 key 状态?

javascript - 如果未选中复选框,如何禁用按钮

c++ - Int(1digit) 到 char 没有任何功能

c - C 中的按位右移赋值运算符

javascript - 从 JSON 读取二维数组

java - 跳棋棋盘 : Representing a two-dimensional array of user-created abstract data types in Java

css - 输入类型 ="file"是否可以将其样式设置为仅文本,如 "upload"