簡體   English   中英

統計C中字符串中的元音個數

[英]Counting the number of vowels in a string in C

在此處輸入圖像描述

我正在用 C 語言解決解密問題

有問題。

有一個計算字符串中元音的過程,

代碼沒有正確讀取該“countingmeasure”中的元音數量

我很好奇,所以我調試了它,

count ++ 在'o' 不起作用。

我真的很好奇為什么會這樣

#include <stdio.h>
int main(void)
{

    char original[15] = { 't','f','l','e','k','v','i','d','v','r','j','l','i','v',NULL };


    printf("암호화된 문자열 : %s\n", original);
    printf("원본 가능 문자열  \n");
    printf("\n");



    for (int j = 0; j < 26; j++)//모음이 7개일때만 출력을 어떻게 시킬까?
    {
        char change[14] = { 0 };
        int counter=0;
        char a;
        

        for (int i = 0; i < 14; i++)
        {   
            a = original[i] + j;

            if (a > 122)
            {
                original[i] -= 26 ;
            }

            if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u')
            {
                counter++;
            }           


            
            printf("%c", original[i] + j);
        }
        printf(" %d\n",counter);
        
    }
}

a = original[i] + j; 沒有任何意義,因為a是一個char ,結果可能不適合它。 具體來說,“字符值+26”可能大於127。char 默認是有符號的還是無符號的?

此外,除'0''9'之外的任何符號的算術運算都沒有明確定義,並且不能保證它們相鄰分配。 另外請不要在源代碼中使用硬編碼的“幻數”。 而不是 122 你應該使用'z'等。

有幾種方法可以修復程序。

  • 快速而骯臟的解決方案是在現有程序上執行unsigned char a ,如果您對“它只是有效,但我什至不知道我在做什么”感到滿意。
  • 更好的解決方案是聲明一個元音字符串,然后對於輸入字符串中的每個字符,在元音字符串中執行strchr()搜索以查找匹配項。 (正確但幼稚且緩慢,足夠好的初學者解決方案。)
  • 一個專業的解決方案是創建一個包含 128 個布爾值的查找表,例如
    const bool LOOKUP [128] = { ['A'] = true, ['a'] = true, ['E'] = true, ... }; 然后檢查if(item[i] == LOOKUP[ item[i] ]) /* then vowel */
  1. 使用函數。
  2. NULL 是一個非零指針或 null 終止符
  3. 使用字符串文字。
  4. 使用標准函數改變大小寫(tolower,toupper)
char *mystrchr(const char *str, const char lt, int ignoreCase)
{
    while(*str) 
    {
        if(ignoreCase) 
            if(tolower((unsigned char)*str) == tolower((unsigned char)lt)) return (char *)str;
        else 
            if(*str == lt) return (char *)str;
        str++;
    }
    return NULL;
}

size_t count(const char *haystack, const char *needle, int ignoreCase)
{
    size_t count = 0;
    while(*haystack)
    {
        if(mystrchr(needle, *haystack, ignoreCase)) count++;
        haystack++;
    }
    return count;
}

int main(void)
{
    char *str = "tflekvidvrjliv";

    printf("%zu\n", count(str, "aeiou", 1));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM