华为机试-计算字符个数

题目描述

写出一个程序,接受一个由字母和数字组成的字符串,和一个字符,然后输出输入字符串中含有该字符的个数。
不区分大小写。

自解

思路:逐个字符判断

#include 
#include 
using namespace std;
int main()
{
    string str = "";
    while(cin >> str) // 这里如果换做 while(getline(cin, str))的话,换行分别输入字符串、字符,会输出两遍
    {
        char ch = '\0';
        cin >> ch;
        int i = 0;
        int count = 0;
        while(str[i] != '\0')
        {
            if((ch == str[i]) || (ch - 32 == str[i]) || (ch + 32 == str[i]))
            {
                ++count;
            }
            ++i;
        }
        cout << count << endl;
    }
    return 0;
}

速度:3ms
大小:484K

其他

思路:
自定义计数函数。
利用库函数find_first_of()查找字符串中指定字符的位置,每找到一个之后再利用find_first_of()的重载,从前面找到指定字符的位置后面开始查找,如此循环。

#include 
#include 
 
int count_char(std::string& str, char c)
{
    std::size_t found = str.find_first_of(c);
    int count = 0;
    while (std::string::npos != found)  // npos用来表示str中未找到字符c
    {
        count++;
        found = str.find_first_of(c, found + 1); // 从找到的位置+1处继续查找
    }
 
    return count;
}
 
int main(int argc, char* argv[])
{
    std::string str;
    char c = 0;
    std::getline(std::cin, str);
    std::cin >> c;
    int count = count_char(str, c);
    if (c >= 'A' && c <= 'Z') 
    {
      count += count_char(str, c + 'a' - 'A');
    } else if (c >= 'a' && c <= 'z') 
    {
      count += count_char(str, c + 'A' - 'a');
    }
    std::cout << count << std::endl;
    return 0;
}

速度:<1ms
大小:242K

你可能感兴趣的:(华为机试练习记录)