首页 > 解决方案 > 在字符串中查找字母返回不同的数字

问题描述

为什么phrase.find("333", 0)return4phrase.find("333", 2)return4一样?

我的程序工作正常吗?不应该在第二个字符之后搜索 333 吗?

int main() {
    string phrase = "text333 fdsfwsawa";
  
    cout << phrase.find("333", 2) << endl;

    return 0;
}

标签: c++

解决方案


size_type find(const basic_string& str, size_type pos = 0) const;

上面我们有一个 Find() 的声明。

返回值: size_type :找到的子字符串的第一个字符的位置,如果没有找到这样的子字符串,则返回 npos。

参数:str:你的输入字符串

pos:在字符串中要从哪个位置开始搜索,默认为 0

#include <string>
#include <iostream>
 
void print(std::string::size_type n, std::string const &s)
{
    if (n == std::string::npos) {
        std::cout << "not found\n";
    } else {
        std::cout << "found: " << s.substr(n) << '\n';
    }
}
 
int main()
{
    std::string::size_type n;
    std::string const s = "This is a string";
 
    // search from beginning of string
    std::cout<< s.find("is");
 
    // search from position 5
    std::cout<< s.find("is", 5);
    
    // find a single character
    std::cout<< s.find('a');
   
}

输出:

2
5
8

在您的问题phrase.find("333", 0)中,它将从位置零开始搜索,并在位置 4 找到“333”。


推荐阅读