当前位置: 首页 > 知识库问答 >
问题:

使用二维数组计算每个字符串中的元音

龚招
2023-03-14

我需要编写一个程序,用户输入字符串的数量,程序计算每个字符串中的元音数量并打印元音总数。以下代码无需二维数组即可工作

int countVoweles(char inputArray[])
{
    int total = 0;
    char vowels[] = "aAeEiIoOuU";
    for (int i = 0; inputArray[i]; i++)
    {
        for (int j = 0; vowels[j]; j++)
        {
            if (inputArray[i] == vowels[j])
            {
                total++;
            }
        }
    }
    return total;
}

但是,以下代码不适用于二维数组。它仅从第一个字符串打印元音。

如何从输入的所有字符串打印元音?

char name[3][10];
    int total = 0;
    char vowels[] = "aAeEiIoOuU";
    printf("Enter your string :");
    for (int i = 0; i < 3; i++)
    {
        gets(name[i]);
    }
    printf("The total number of vowels are :\n");
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; name[i][j]; j++)
        {
            if (name[i][j] == vowels[i])
            {
                total++;
            }
        }
    }
    printf("%d", total);

共有2个答案

潘俊
2023-03-14

您的函数需要知道2D字符数组的大小。

size_t countVoweles(size_t lines, size_t chars, char inputArray[lines][chars])
{
    size_t total = 0;
    const char vowels[] = "aAeEiIoOuU";
    for (size_t i = 0; i < lines; i++)
    {
        for (size_t j = 0; inputArray[i][j]; j++)
        {
            total += !!strchr(vowels, inputArray[i][j]);
        }
    }
    return total;
}

int main(void)
{

    char x[][256] = {
        "<Compilation failed>",
        "# For more information see the output window",
        "# To open the output window, click or drag the \"Output\" icon at the bottom of this window",
    };
    printf("%zu\n", countVoweles(sizeof(x)/ sizeof(x[0]), sizeof(x[0]), x));
}
常永怡
2023-03-14

对于初学者,请注意函数get是不安全的,并且不受C标准的支持。相反,请使用标准函数fget作为示例

fgets( name[i], sizeof( name[i] ), stdin );

至于您的问题,那么您还需要一个循环来遍历带有元音的数组,以获取数组name字符串中的给定字符。

举个例子。

for (int i = 0; i < 3; i++)
{
    for (int j = 0; name[i][j]; j++)
    {
        int k = 0;
        while ( vowels[k] && name[i][j] != vowels[k] ) ++k;
        if ( vowels[k] )
        {
            total++;
        }
    }
}

另一种方法是使用你已经编写的函数,如

for (int i = 0; i < 3; i++)
{
    total += countVoweles( name[i] );
}

与其使用循环遍历数组元音,不如使用标头中声明的标准 C 函数 strchr

for (int i = 0; i < 3; i++)
{
    for (int j = 0; name[i][j]; j++)
    {
        total += strchr( vowels, name[i][j] ) != NULL;
    }
}

 类似资料:
  • 在C++中将二维字符数组复制到一维数组字符串中最简单的方法是什么? 大概是这样的: 问候蒂尔曼

  • 问题内容: 这是来自pyschools的问题。 我确实做对了,但我猜测会有一个更简单的方法。这是最简单的方法吗? 看起来应该像这样: 问题答案: 在2.7+中: 较早的版本(2.5或更高版本,到目前为止):

  • 本文向大家介绍使用MySQL计算字符串中的字符数,包括了使用MySQL计算字符串中的字符数的使用技巧和注意事项,需要的朋友参考一下 今天,我需要从一个表中获取一些数据,该表中另一个字符串中不止一个字符串出现。基本上,我需要从一个表中查找所有深度超过3级(即带有3个斜杠)的URL,但是意识到在MySQL中没有函数可以执行此操作。我找到了另一种方法,但它使我思考如何可能。 找到解决方案并不是很困难,我

  • 我试图计算2D数组的每个元素,但出于某种原因,我做错了:

  • 给定 我想使用Java8流像下面这样打印 。 使用以下内容: 但不起作用。

  • 问题内容: 我在做作业时遇到了这个问题(老实说,至少没有试图隐藏它),在解决该问题时遇到了问题。 给定以下声明:字符串短语=“ WazzUp?-谁在第一时间???-IDUNNO”;编写必要的代码以计算字符串中的元音数量,并将适当的消息打印到屏幕上。 这是我到目前为止的代码: 但是,当我运行它时,它只会产生一堆空白行。有人可以帮忙吗? 问题答案: 应该是。 给出的值,然后加1。就像您现在拥有的一样,