计算句子中每个单词的元音和字符

标签 c character

我一直在努力弄清楚如何计算句子中每个单词中的元音和字符。 例如

hello there句中

你好:5 个字符,2 个元音

有:5 个字符,2 个元音。我已经看到了为一个完整的句子做同样事情的代码。但不是逐字逐句。

下面是我一直在做的代码

int main() {
    char str[512] = "hello there", word[256];
    int i = 0, j = 0, v, h;
    str[strlen(str)] = '\0';

    /* checking whether the input string is NULL */
    if (str[0] == '\0') {
        printf("Input string is NULL\n");
        return 0;
    }

    /* printing words in the given string */
    while (str[i] != '\0') {
        /* ' '  is the separator to split words */
        if (str[i] == ' ') 
        {
            for (h = 0; word[h] != '\0'; ++h)
            {
                if (word[h] == 'a' || word[h] == 'e' || word[h] == 'i' || word[h] == 'o' || word[h] == 'u')++v;
            }
            printf("\nVowels: %d", v);
            word[j] = '\0';

            printf("%s\n", word);
            j = 0;
        } 
        else 
        {
            word[j++] = str[i];
        }
        i++;
    }

    word[j] = '\0';

    /* printing last word in the input string */
    printf("%s\n", word);
    return 0;
}

输入将全部小写。我很难弄明白这一点。

在运行代码时,我没有得到元音计数。我可以拆分句子。但是元音计数并没有发生。

最佳答案

一个相当简单的方法:

#include <stdio.h>

const char* s(int n)
{
    return n == 1? "" : "s";
}

void count (const char* str)
{
    for (int i = 0;;)
        for (int v = 0, w = i;;)
        {
            int len;
            char c = str[i++];
            switch (c)
            {
            case 'a': case 'e': case 'i': case 'o': case 'u':
                v++;
            default:
                continue;
            case ' ': case '\t': case '\n': case '\0':
                len = i - 1 - w;
                printf("'%.*s': %d character%s, %d vowel%s\n", len, str+w, len, s(len), v, s(v));
                if (c)
                    break;
                else
                    return;
            }
            break;
        }
}


int main(void)
{
    count("My words with vowels");
    return 0;
}

关于计算句子中每个单词的元音和字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24925383/

相关文章:

c++ - 矢量化图像处理

c - gethostbyname 有什么问题?

c - 可重用嵌入式 C 的最佳实践?

c - 如果输入到字符数组中的字符数少于指定的空格数,会发生什么情况

string - 声明char以防 rust

c++ - 为什么 strlen(s) 与 s 的大小不同,为什么 cout char 显示的是字符而不是数字?

c# - 字符转换为位图图像 C#

c - 将 argv[1] 存储到一个 char 变量

c - C 是否具有函数参数名称的 __func__ 功能?

ios - 如何获取 textField 文本范围直到 6 个字符?