我是新手C程序员。我想在字符串中打印重复的字母。首先,用户输入字母,然后getchar()收集并将它们放置在数组中。之后,应扫描此数组,并应打印程序“字符重复x次”。例如:A重复5次。这是我的源代码,我编写了此代码,但遇到了一些问题。我想打印一个字母的重复次数,而不应该再次打印。
#include <stdio.h>
#include "stdlib.h"
#include <locale.h>
#include <wchar.h>
int main()
{
wchar_t message[100];
wint_t ch;
int i = 0;
setlocale(LC_ALL, "");
wprintf(L"Enter your message: ");
while ((ch = getwchar()) != '\n')
{
message[i] = ch;
i++;
}
for (int j = 0; j < i; j++)
{
int repeated = 1;
for (int k = j + 1; k < i; k++)
{
if (message[j] == message[k])
repeated++;
}
wprintf(L"%lc is repeated %d times.\n", message[j], repeated);
}
printf("\n\n");
return 0;
}
正确的输出应该是:
a is repeated 5 times.
b is repeated 5 times.
c is repeated 5 times.
我该怎么做?
使用数组计算每个wchar_t
值的出现数
类似:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
int main(void) {
int sz = 1;
for (int i=0; i < sizeof(wchar_t); ++i) sz = sz * 8;
unsigned* arr = malloc(sz * sizeof *arr);
memset(arr, 0, sz * sizeof *arr);
wchar_t text[] = L"Hello world";
wchar_t* p = text;
while(*p != '\0') ++arr[*p++];
for (unsigned i = 0; i<sz; ++i) if (arr[i]) printf("[%lc] %u\n", i, arr[i]);
free(arr);
return 0;
}
输出:
[ ] 1
[H] 1
[d] 1
[e] 1
[l] 3
[o] 2
[r] 1
[w] 1