在字符串中查找字符

时间:2017-09-18 04:07:29

标签: c++

我无法让char搜索工作。 substring函数正在工作,但char搜索不能提供它正在寻找的char的正确位置

<input id="guess" type="text">
<br />
<button id="submit" type="submit">Guess 1</button>
<button id="submit2" type="submit">Guess 2</button>
<button id="submit3" type="submit">Guess 3</button>
<p id="result"></p>
<p id="hotCold"></p>
<h2>Your guesses</h2>
<p id="prevGuesses"></p>

3 个答案:

答案 0 :(得分:2)

要在字符串中查找字符,您有两个接口。

  1. std::string::find将返回您找到的角色的位置:

    auto pos = yourStr.find('h');
    char myChar = yourStr[pos];
    
  2. 如果该字符不存在,则std::string::npos将返回std::size_t返回的位置。

      标题stl algorithm中的
    1. std::find algorithm返回一个迭代器:

      auto it = std::find(yourStr.begin(), yourStr.end(), 'h');
      char myChar = *it;
      
    2. 如果角色不存在,则it == yourStr.end()

答案 1 :(得分:1)

CharSearch方法存在一些愚蠢的错误。首先,当你得到目标角色时,你必须打破循环。最重要的是,当您找到目标时,您不会分配x。此外,循环内还有额外的值i增量。我修改了这个功能。请在下面查看

int charsearch(string searchInto, char ch, int start = 0) {

    int x = -1;
    long n = searchInto.length();
    for (int i = start; i < n; i++)
    {
        cout << ch;
        if (searchInto[i] == ch)
        {

           x = i; // previously written as i = x which is wrong
           break; // loop should break when you find the target
        }
     }

     cout<< x;
     return x;
}

请注意,您也可以使用find的{​​{1}}方法或string的{​​{1}}来搜索字符串。

答案 2 :(得分:-1)

您需要根据此代码进行更改

int charsearch(string searchInto, char ch, int start = 0)
{
    int x = -1; // : change,  if return -1, means not found 
    long n = searchInto.length();
    for (int i = start; i < n; i++) // : change
    {
        cout << ch;
        if (searchInto[i] == ch)
        {
            x = i; // : change
            break; // : change
        }
    }
    cout<< x;
    return x;
}

注意:此功能将返回第一场比赛。