检查字符串的每个元素是否有数字或字符

时间:2014-12-11 02:51:28

标签: c++ string

我正在尝试制作一个程序,告诉用户键入一个句子或其他内容。 然后我需要找到字符串中有多少数字,字符,所有其他数字(符号,句点,空格等......)。

为什么我的代码不起作用?我认为它与find_first_of一次检查整个字符串有关,而我希望它只检查索引“i”的位置。

[错误]请求's1.std :: basic_string< _CharT,_Traits,_Alloc> :: operator [],std :: allocator>中的成员'find_first_of'((标准: :basic_string :: size_type)i))',它是非类型'char' ,是我在下面两条注释代码行中得到的错误。

#include <iostream>
#include <string>


using namespace std;

int main ()
{
    string s1;
    int numbers = 0;
    int characters = 0;
    int others = 0;

    cout << "Please type in Something: ";
    getline(cin, s1);
    cout << "You typed: " << s1 << endl;

    for(int i = 0; i < sizeof(s1) / sizeof(string); ++i)
    {
        if(s1[i].find_first_of("123456789") != string::npos) // Here is where the compiler errors
        {
            ++numbers;
        }
        else if(s1[i].find_first_of("AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz") != string::npos) // And here with the same error
        {
            ++characters;
        }
        else
        {
            ++others;
        }
    }
    cout << "Total numbers in the string are: " << numbers << endl << "Total characters in the string are: " << characters << endl << "Total special characters, symbols, spaces etc... are: "<< others; 

    return 0;
}

2 个答案:

答案 0 :(得分:1)

关于错误,s1[i]是单个字符,它不是std::string,因此在调用find_first_of时尝试将其用作字符串对象将不起作用(不编译)。


您的代码至少还有两个问题:

问题1:

std::string通过调用size()方法知道它有多少个字符。因此,这是错误的:

 for(int i = 0; i < sizeof(s1) / sizeof(string); ++i)

应该是:

 for(size_t i = 0; i < s1.size(); ++i)

问题2:

不需要使用string::find_first_of。有些函数可以确定字符是否为字母和数字。

    #include <cctype>
    //...
    if (std::isdigit(s1[i]))
        ++numbers;
    else 
    if (std::isalpha(s1[i]))
        ++characters;
    else
        ++others;

std :: isdigit:http://en.cppreference.com/w/cpp/string/byte/isdigit

std :: isalpha:http://en.cppreference.com/w/cpp/string/byte/isalpha

答案 1 :(得分:1)

代码存在许多问题: 1.你不能在角色上调用find_first_of 2. find_first_of无济于事

#include <iostream>
#include <string> 
#include <cctype>

using namespace std;

int main ()
{
string s1;
int numbers = 0;
int characters = 0;
int others = 0;

cout << "Please type in Something: ";
getline(cin, s1);
cout << "You typed: " << s1 << endl;

for(size_t i = 0; i < s1.size(); ++i)
{
    if(isdigit(s1[i])){++numbers;}       
    else if(isalpha(s1[i])){++characters;}
    else{ ++others;}
}

cout << "Total numbers in the string are: " << numbers << endl 
<< "Total characters in the string are: " << characters << endl 
<< "Total special characters, symbols, spaces etc... are: "<< others<<endl; 

return 0;

}