我不确定我在下面的代码中做错了什么,
这就是我想要的
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/