C ++:find(str,ind)返回几个-1

时间:2017-06-01 21:20:33

标签: c++ string find

作为一个例子,如果我进入"爱"作为字符串并搜索字符" o,"我明白了:

  • 找到1,位置:0
  • 找到1并且职位:1
  • 找到-1和位置2
  • 角色的最后位置:-1,索引为:3

另一个例子,如果我输入:"我爱你"并搜索字符" v,"我明白了:

  • 发现:4和位置:0
  • 发现:4和位置:1
  • 发现:4和位置:2
  • 发现:4和位置:3
  • 发现:4和职位:4
  • 找到:-1和位置:5
  • 找到:-1和位置:6
  • 找到:-1和位置:7
  • 找到:-1和位置:8

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string str;
    char ch;
    int i, found;

    cout << "Please input a string: ";
    getline (cin, str);

    cout << "Please input a character: ";
    cin.get(ch);

    cout << "The string is: " << str << " and the character is: " << ch << endl;
    cout << "The string length is: " << str.length() << endl;

    for (i = 0; i < str.length()-1; i++)
    {

        found = str.find(ch, i);
        cout << "Found: " << found << " and Position: " << i << endl;

        if (i == str.length())
        {
            i = found + 1;
            break;
        }
    }
    cout << "The character's last position: " << found << " and the index is: " << i << endl;

    return 0;
}

我不知道自己做错了什么,但是&#34; -1&#34;(s)给我带来了问题。我只想找到角色的位置,因为我遍历字符串寻找角色。任何帮助将不胜感激。

我在教自己C ++,这是本书中的一个问题。我应该使用found。问题陈述:

(程序)编写一个C ++程序,它接受来自用户的字符串和单个字符。程序应确定字符串中包含字符的次数。 (提示:使用find(str,ind)函数搜索字符串。此函数应该在一个循环中使用,该循环将索引值设置为0,然后将索引值更改为1,超过上次找到char的索引。)

参考文献:

[1] Bronson,Gary J ..工程师和科学家的C ++(第543页)。 Cengage教科书。 Kindle版。

2 个答案:

答案 0 :(得分:0)

看一下c++ reference on string::find您使用的变体(4)读取

size_t find (char c, size_t pos = 0) const;

其中参数解释为

pos
   Position of the first character in the string to be considered in the search.
   If this is greater than the string length, the function never finds matches.
   Note: The first character is denoted by a value of 0 (not 1): A 
   value of 0 means that the entire string is searched.

c
   Individual character to be searched for.

在返回值下我们找到

The position of the first character of the first match.
If no matches were found, the function returns string::npos.

让我们通过一些示例,让我们看一下love因为它更短,我们会看string("love").find('o', i) i范围从02 < string("love").length() - 1 = 3

i = 0

love
^ first considered char
 ^ reported find so return value is 1

i = 1

love
 ^ first considered char
 ^ reported find so return value is 1

i = 2

love
  ^first considered char
  -- no match after that position, so return value is string::npos (== -1 most implementations) 

答案 1 :(得分:0)

没有错:

如果找不到这样的子字符串,

std::basic_string::find返回找到的子字符串npos的第一个字符的位置

static const size_type npos = -1;