C++函数来检查 char 是否是大写字母,并且不计算给定字符串中的大写字母

C++ function to check if char is a capital letter and compute no of capital letters in a given string

本文关键字:大写字母 计算 字符串 函数 检查 char 是否是 C++      更新时间:2023-10-16

我试图编写一个C++函数来检查字符是否是给定字符串中的大写字母。

这是我的尝试:

#include<iostream>
#include <conio.h>
#include<string>
using namespace std;
int iscapital(char x)
{
 if (x>='A'&&x<='Z')    return 1;
 else  return 0;
}
main()
{
char a[20];int len; int c=0;
cout<<"enter your line: ";
cin>>a;
len=strlen(a);
for (int i=0;i<=len;i++)
iscapital(a[i]);
if (iscapital)
{
    c++;
}
cout<<"capital letter in string is: "<<c;
}

你的代码应该看起来像这样:

int iscapital(char x)
{
       if (x >='A' && x <= 'Z')    return 1;
       else  return 0;
}
int main()
{
  char a[20];int len; int c=0;
  cout<<"enter your line: ";
  cin.getline(a , 20);      
  // Note : ' getline ' will read the entire line written in the console and will stop only at the end line mark...will include and the white spaces .
  // http://stackoverflow.com/questions/4745858/stdcin-getline-vs-stdcin
  len=strlen(a);
  for (int i = 0;i < len;i++)
  {
    if (iscapital(a[i]))
    {
       c++;
    }
  }
  cout<<"capital letter in string is: "<<c;
  return 0;
 }

您没有正确使用iscapital

for (int i=0;i<=len;i++)
    iscapital(a[i]); // Call the function, ignore the result
if (iscapital)   // <- This is not valid C++
{
    c++;
}

你想要的是这个

for (int i=0;i<=len;i++)
    if (iscapital(a[i]))
    {
        c++;
    }

正如其他人所评论的那样,查找 std::isupper 以了解字母是否是大写字母,查找 std::count, std::count_if 来计算值的出现次数或条件为真的次数。

此外,main应返回intiscapital应返回bool。使用 int 表示真值或假值已经过时,不应在新代码中使用。最后,考虑使用 std::string 而不是 char [] 。使用字符数组来表示字符串是 C 的做事方式。C++使用std::string其中许多微妙的问题。

更正您的代码:

  • IsCapital()应该返回布尔值而不是整数。

  • for (int i=0; i<=len; i++)您正在使用 a[len] 的这个,因此请将其更正为:

for (int i = 0; i <len; i++)

  • 这是什么if (iscapital) { c++;}? 这不是如何调用函数isCapital调用它添加()和参数。

  • 在循环内而不是在循环外部if(iscapital),如您所知,只要不添加括号,您的循环在这里只有一个语句。

所以代码将如下所示:

bool iscapital(char x)
{
    if (x >= 'A' && x <= 'Z')
        return 1;
    else
        return 0;
}
main()
{
    char a[20];
    int len;
    int c = 0;
    cout << "enter your line: ";
    cin >> a;
    len = strlen(a);
    for(int i = 0; i < len; i++)
    {
        if (iscapital(a[i]))
            c++;
    }
    cout << "capital letter in string is: " << c;
    return 0;
}