我想建立自己的功能,删除重复的字符会帮助你实现你正在尝试做的。但是,没有标准函数可以帮助您从字符串中删除所有重复项。因此,请尝试构建一个函数来从字符串中删除所有重复/重复的字符并返回该字符串。这是你的功能是什么样子:
char* remove_duplicated(char* str, int size) {
int frequency[256] = {0};
char* new_str = malloc(size);
int new_size = 0;
for(int i=0; str[i]!='\0'; i++)
{
if(frequency[(unsigned char) str[i]] == 0) {
frequency[(unsigned char) str[i]]++;
new_str[new_size] = str[i];
new_size++;
}
}
new_str[new_size] = '\0';
return new_str;
}
一旦你已经构建了上述功能,在发送要具有测量字符的频率和存储返回字符串的字符串。事情是这样的:
char* new_str = remove_duplicated(str, size);
现在在双for
循环,你正在使用,使用new_str
为您外for循环,还可以使用它为for
循环显示count
for(i=0; new_str[i]!='\0'; i++)
{
for(j=0; str[j]!='\0'; j++)
{
if(new_str[i] == str[j])
count[i]++;
}
}
for(i=0; new_str[i]!='\0'; i++)
printf("%c occurs %d times \n", new_str[i], count[i]);
不要忘记释放remove_duplicated函数中的mableced数组:
free(new_str);
这是一个在线演示:https://ideone.com/KnkwGX
'count'的定义是什么?你的代码实际上是计算完全随机的东西你不需要内部循环,但是你需要一个计数数组,其索引是'str [i]' - 字符串中第i个字符的ASCII码。 – DyZ
like [this](http://ideone.com/Ns9quD) – BLUEPIXY
@DYZ:完全随机并不准确 - 它被定义,但不是想要的。我同意双循环是不必要的,但你已经夸大了你的情况。对于出现两次的信件,计数将是4;对于出现三次的信,计数将是9;对于出现N次的信件,计数将是N 2。 –