簡體   English   中英

C ++在字符串中查找重復的子字符串

[英]c++ find repeated substring within string

我試圖找到子字符串在字符串輸入中重復的次數,但是由於某種原因,當我調用該函數時,它給了我一個奇怪的數字。 我已經在main中測試了該功能,並且可以正常工作,但是當我創建一個獨立功能時,它不起作用。

先感謝您

#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int checkHope(string word1)
    {
    int answer;
    int counter;
    for(int i = 0; word1[i] != '\0'; i++)
    {
        answer = word1.find("h", i);
        if ((word1.find("o", (answer+1)) == i+1) && (word1.find("e", (answer+3)) == i+3)) counter++;
    }
    return counter;
    }

int main()
{
    string word1;

    cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
    getline(cin, word1);
    cout << checkHope(word1);

    return 0;
}
//This will work, 
//Changes initialize counter to 0, add condition to check alphabet 'p' also in if condition


#include <iostream>
#include <cstring>
#include <string>

using namespace std;

int checkHope(string word1)
{
  int answer;
  int counter=0;
  for(int i = 0; word1[i] != '\0'; i++)
  {
    answer = word1.find("h", i);
    if ((word1.find("o", (answer+1)) == i+1)
          &&  (word1.find("p", (answer+2)) == i+2)
          && (word1.find("e", (answer+3)) == i+3))
           counter++;
  }
  return counter;
}

int main()
{
  string word1;

  cout << "Please enter a word to check how many times the word \"hope\" appears. You can also have any letter instead of p.: ";
  getline(cin, word1);
  cout << checkHope(word1);

  return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM