首页 > 解决方案 > 如何设置控制机制来查找重复的字母?

问题描述

我是一个新手 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.

我怎样才能做到这一点?

标签: carraysfor-loopcontrols

解决方案


您需要一种方法来标记您已经计数的字符,这样您就可以避免再次计数字符。

您可以通过使用第一个字符作为标记来做到这一点,这意味着“已计入,因此请跳过此字符”。您可以通过更改与第一个字符相等的字符来实现。当您在字符串中移动时,您只需跳过等于第一个字符的字符。

例子:

假设文本 i "HelloHey" 然后它就像:

1. iteration "HelloHey" -> "HelloHey" and print "H 2 times"
2. iteration "HelloHey" -> "HelloHHy" and print "e 2 times" (second e replaced by H)
3. iteration "HelloHHy" -> "HelHoHHy" and print "l 2 times" (second l replaced by H) 
4. iteration skip because of an 'H' in position 4 of "HelHoHHy"
5. iteration "HelHoHHy" -> "HelHoHHy" and print "o 1 time" 
6. iteration skip because of an 'H' in position 6 of "HelHoHHy"
7. iteration skip because of an 'H' in position 7 of "HelHoHHy"
8. iteration "HelHoHHy" -> "HelHoHHy" and print "y 1 time" 

代码可能如下所示:

#include <stdio.h>
#include <wchar.h>

int main(void) {
    wchar_t text[] = L"Hello world";
    wchar_t* p = text + 1;
    unsigned i = 1;

    // Unconditional loop to count first letter
    while(*p)
    {
        if (*p == text[0])
        {
            ++i;
        }
        ++p;
    }
    printf("[%lc] seen %u times\n", text[0], i);

    // Loop the remaining string
    p = text + 1;
    while(*p)
    {
        // Only count if current letter differs from first letter
        if (*p != text[0])
        {
            // New character - count its occurence
            wchar_t* t = p + 1;
            unsigned i = 1;
            while (*t) 
            {
                if (*p == *t) 
                {
                    ++i; 
                    *t = text[0];   // Mark letter as counted
                }
                ++t;
            }
            printf("[%lc] seen %u times\n", *p, i);
        }
        ++p;
    }
    return 0;
}

输出:

[H] seen 1 times
[e] seen 1 times
[l] seen 3 times
[o] seen 2 times
[ ] seen 1 times
[w] seen 1 times
[r] seen 1 times
[d] seen 1 times

推荐阅读