我不知道在下面的代码中我做错了什么,
这就是我想要达到的
用户输入: aaaaaadsssssc 输出: 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);
}我几天后就该付这个了,我搞砸了。有人能指出我正在犯的错误吗?提前表示感谢!
发布于 2016-02-06 22:46:21
这将起作用:
#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");
}https://stackoverflow.com/questions/35247331
复制相似问题