【问题标题】:How to count uppercase letter in each word in a 2D string如何计算二维字符串中每个单词的大写字母
【发布时间】:2022-01-14 08:44:11
【问题描述】:

我试图使用 C 找出 2D 字符串中每个单词的大写字母。但我没有弄清楚逻辑。我假设这个结果 -

示例输入

2
Dhaka
apple

样本输出

1
0

这是我的代码 -

#include<stdio.h>
#include<string.h>

int main()
{
    int count = 0, num;
    char str[50][50];

    printf("How many word you want to enter: ");
    scanf("%d", &num);

    printf("\nEnter any word: ");

    for(int i=0; i<num; i++)
    {
        for(int j=0; j<num; j++)
        {
            gets(str);
        }
    }

    for(int i=0; str[i]!='\0'; i++)
    {
        for(int j=i+1; j<num; j++)
        {
            if(str[i] >= 'A' && str[i] <= 'Z')
            {
                count++;
            }
        }
    }

    printf("\n%d\n", count);

    return 0;
}

【问题讨论】:

  • 索引全乱了。您正在分配一个由 50 个字符串组成的 2D 数组,每个字符串 50 个字符,但您只索引到数组的 1D 并将用户输入读取到同一位置,从而覆盖数据。计数索引也是错误的;你需要考虑str[i][j]。尝试通过一次只做一个字符串并在外面循环,阅读单词并计算字母来简化它。
  • 注意编译器警告。当需要char* 时,它应该抱怨使用char(*)[50]。哦!并避免使用gets(),因为它不再是标准 C 的一部分(不可能安全地使用它)。

标签: c string


【解决方案1】:

来源:

#include<stdio.h>
#include<string.h>
#include<ctype.h>

int main(){
    int count = 0, num;
    //Enter how many lines you want to enter
    printf("How many lines you want to enter: ");
    scanf("%d", &num);

    char str[num][100];

    //printf("\nEnter any word: ");

    for(int i=0; i<num; i++){
        //flushs the previous buffer
        getchar();
        //Press enter to enter a line
        scanf("%[^\n]",str[i]);
    }

    for(int i=0;i<num; i++,count=0){
        for(int j=0; str[i][j]!='\0'; j++){
            //printf("%c",str[i][j]);

            //if(str[i][j] >= 'A' && str[i][j] <= 'Z'){
            //  count++;
            //}
            if( isupper(str[i][j]) )
                count++;
        }
        printf("\n%d\n",count);
    }

    return 0;
}

输出:

$ gcc string.c && ./a.out
How many lines you want to enter: 3
djjdjd JJ
j3j3j3j JJJJJKK
$#jjd

2

7

0

【讨论】:

  • 考虑使用来自ctype.hisupper()
  • 你对scanf()的使用并不比OP对gets()的使用好。
猜你喜欢
  • 2014-05-19
  • 2010-12-05
  • 2011-01-20
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
相关资源
最近更新 更多