我有一個 C 程式,旨在從給定的輸入字串中回傳重復字符及其頻率。目前,它作業得很好,但是我想知道是否有一種方法可以更改它,以便它按出現順序回傳字符,而不是按字母順序(?)順序。
# include <stdio.h>
# include <stdlib.h>
#include <ctype.h>
# define NO_OF_CHARS 256
char fillCharCounts(unsigned char *str, int *count)
{
int i;
for (i = 0; *(str i); i )
count[*(str i)] ;
return 0;
}
void printDups(unsigned char *str)
{
int *count = (int *)calloc(NO_OF_CHARS,
sizeof(int));
fillCharCounts(str, count);
int dupe_chars = 0;
int i;
for (i = 0; i < NO_OF_CHARS; i )
if (count[i] > 1) {
printf ("\nDuplicate letter: %c, Occurrences: %d", i, count[i]);
dupe_chars;
}
if (0 != dupe_chars)
printf ("\n");
else
printf ("\nNo duplicates found\n");
free(count);
}
int main()
{
unsigned char str[15] = "";
printf("Enter a word>");
scanf("%s", str);
printDups(str);
getchar();
return 0;
}
目前,如果輸入字串是“zzbbaa”,它會給出輸出;
“重復:a,計數:2” “重復:b,計數:2” “重復:z,計數:2”
如何更改此設定,以便輸出按字串中出現的順序回傳重復項?
uj5u.com熱心網友回復:
您可以再次檢查字串,在第一次找到重復項時列印出來。
這是我會寫的代碼。不需要動態分配記憶體——count陣列可以入堆疊,而且*(str i)寫得更好str[i]。
#include <stdio.h>
#include <limits.h>
void printDups(unsigned char *s) {
int count[UCHAR_MAX 1] = {0};
int dupes = 0;
for (int i = 0; s[i]; i ) {
count[s[i]] ;
dupes = dupes || (count[s[i]] > 1);
}
for (int i = 0; s[i]; i ) {
if (count[s[i]] > 1) {
printf("Duplicate letter: %c, Occurrences: %d\n", s[i], count[s[i]]);
count[s[i]] = 0;
}
}
if (!dupes) {
printf("No duplicates found\n");
}
}
int main(int argc, char**argv) {
unsigned char s[] = "hello world";
printDups(s);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/450530.html
下一篇:在二維陣列中列印每一行兩次-C
