首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用c- Basic语言压缩单词

问用c- Basic语言压缩单词
EN

Stack Overflow用户
提问于 2016-02-06 22:34:47
回答 1查看 51关注 0票数 2

我不知道在下面的代码中我做错了什么,

这就是我想要达到的

用户输入: aaaaaadsssssc 输出: a6ds5c

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

代码语言:javascript
复制
#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);
}

我几天后就该付这个了,我搞砸了。有人能指出我正在犯的错误吗?提前表示感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-06 22:46:21

这将起作用:

代码语言:javascript
复制
    #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");
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35247331

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档