std::string如何查找全部出现的字符
时间: 2023-08-03 17:08:41 浏览: 51
std::string中可以使用find函数的重载版本来查找全部出现的字符。具体方法是:
```c++
std::string str = "hello world";
std::string sub_str = "l";
size_t pos = str.find(sub_str);
while (pos != std::string::npos) {
std::cout << "子串出现的位置为:" << pos << std::endl;
pos = str.find(sub_str, pos+1);
}
```
在这个例子中,我们首先使用find函数查找子串在字符串中第一次出现的位置,然后在while循环中不断调用find函数,并将上一次查找到的位置加1作为下一次查找的起始位置。当find函数返回std::string::npos时,表示字符串中没有找到子串,循环结束。
需要注意的是,在使用find函数查找全部出现的字符时,我们需要将上一次查找到的位置加1作为下一次查找的起始位置。这是因为,find函数默认从字符串的起始位置开始查找,如果不加1的话,会重复查找已经查找过的位置。
另外,如果需要查找多个字符,可以将查找的子串设为单个字符,然后使用循环查找全部出现的字符。
相关问题
std::string 字符串查找
你可以使用 std::string 类型的 find() 函数来查找子字符串。find() 函数返回子字符串在字符串中的位置,如果找不到则返回 std::string::npos.
下面是一个示例代码:
```c++
#include <iostream>
#include <string>
int main()
{
std::string str = "Hello, world!";
std::string sub_str = "world";
size_t found = str.find(sub_str);
if (found != std::string::npos)
{
std::cout << "Substring found at position: " << found << std::endl;
}
else
{
std::cout << "Substring not found." << std::endl;
}
return 0;
}
```
输出结果:
```
Substring found at position: 7
```
在上面的代码中,我们首先定义了一个字符串 str 和一个子字符串 sub_str,然后使用 find() 函数查找子字符串在字符串中的位置。如果子字符串存在,则打印其位置,否则打印“Substring not found.”。
std::string 查找字符串
您可以使用C++中的`std::string::find()`函数来查找一个字符串中是否包含另一个字符串。
例如,如果您想要查找字符串`str`是否包含子字符串`subStr`,您可以使用以下代码:
```cpp
std::string str = "Hello World";
std::string subStr = "World";
if (str.find(subStr) != std::string::npos) {
std::cout << "Substring found in the string!" << std::endl;
} else {
std::cout << "Substring not found in the string." << std::endl;
}
```
在上述代码中,`std::string::find()`函数返回子字符串`subStr`在`str`中的位置。如果子字符串不在字符串中,则返回`std::string::npos`。因此,我们可以检查返回值是否等于`std::string::npos`来判断是否找到了子字符串。