带可互换字母的字符串

Chr*_*oph 2 c++ string function

我的任务指示如下:

返回字符串"hope"出现在给定字符串中的任何位置的次数,除了我们将接受任何字母'p',所以"hode"和"hooe"计数.

我正在努力弄清楚如何使第三个字母等于任何东西,并且仍然让程序确定它是正确的.

到目前为止,我的代码显然是错误的,但仍然包含它.

一个大问题是我无法告诉数组检查它是否与字符串匹配.

int wordsFunction(string words)
{
int num = 0;

for(int i = 0; i < words.length(); i++)
{
    if(words[i] == "Hope" || words[i] == "hope")
    {
        num++;
    }
}
return num;
}

main()
{
string words;
cout << "Enter a string: ";
getline(cin, words);
cout << wordsFunction(words);
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

到目前为止我的代码显然是错误的

那是真实的.我不会解释为什么你的代码是错误的,直接进入修复的描述.

main读取允许空格的字符串,这很好:代码的I/O部分不需要更改.

现在观察到检测字"ho*e",有*表示任何单个字符,在一个位置i一个字w,你需要检查w[i]'h',w[i+1]'o',w[i+3]是的'e',那该指数i+3是有效的.这变成了一个简单的检查:

if (i+3 < w.size() && w[i] == 'h' && w[i+1] == 'o' && w[i+3] == 'e') {
    count++;
}
Run Code Online (Sandbox Code Playgroud)