c - 挤压c中的单词——C语言基础

标签 c

我不确定我在下面的代码中做错了什么,

这就是我想要的

User Input: aaaaaadsssssc

Output: a6ds5c

我的程序一直运行良好,直到今天早上我才愚蠢到覆盖整个文件。哦,好吧,欢迎来到 Linux!由于我重写了程序,它给我段错误,我不知道我在这里做错了什么,此时我的头脑停止了工作。

#include <stdio.h>
#include <string.h>

int main(){
        int i, j, k, count;
        char str[1000];

        printf("Enter: ");
        scanf("%[^\n]s", str);
        printf("You have typed: %s\n", str);

        printf("length: %d\n", strlen(str));
        for (i = 1; i < strlen(str); i++){
                count = 2;

                if (str[i] == str[i-1]){
                        j = i;
                        while (str[i] == str[i+1]){
                                if (k != strlen(str)){str[k] = str[k+1];}
                                else{str[k] = '\0';}
                                i++; k++; count++;
                        }
                str[j] = count;
                k++;
                }
        }
        str[k] = '\0';
        printf("output: %s\n", str);
}

几天后我就要到期了,但我搞砸了。有人可以指出我犯的错误吗?非常感谢!

最佳答案

这会起作用:

    #include <stdio.h>
    #include <string.h>

    int main(){
            int i, count;
            char str[1000];

            printf("Enter: ");
            scanf("%s", str);
            printf("You have typed: %s\n", str);

            //used strlen() only once because strlen() takes O(n) time
            int len = strlen(str);
            printf("length: %d\n", len);

            //iterate through the string
            for (i = 0; i < len - 1; i++){

                    //every char appears at least once
                    count = 1;

                    //print the char regardless of it repeating
                    printf("%c", str[i]);
                    for (int j = i; str[j] == str[j+1]; ++j, ++i)
                            ++count;

                    //print the count if it's greater than 1
                    if (count > 1) printf("%d", count);
            }

            //print the last char if it's different from the second last
            if (str[len - 1] != str[len - 2]) printf("%c", str[len - 1]);

            //print new line
            printf("\n");
    }

关于c - 挤压c中的单词——C语言基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35247331/

相关文章:

c - C中的复数问题

c - 关于 int 未定义增量的警告

C 字符串格式化等效项

c - strtok 和 strcpy 错误

objective-c - 为什么负 NSInteger(长整型)值在通过可变参数发送时会变成垃圾?

c - 求余弦的泰勒级数

c - 为什么 h_addr_list (在 hostent 结构中)类型为 char** 而不是 void*?

c - 如何使用 C 语言对结构中的字符名称进行排序

c - fprintf 不写任何东西

c - 在 Visual Studio 2005 中使用 WinDDK 测试实用程序