string查找子字符串
时间: 2023-11-14 07:06:17 浏览: 35
可以使用 string 类的 find() 方法来查找子字符串在字符串中的位置,示例如下:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "Hello, world!";
string sub_str = "world";
size_t pos = s.find(sub_str);
if (pos != string::npos) {
cout << "Substring found at position " << pos << endl;
} else {
cout << "Substring not found" << endl;
}
return 0;
}
```
输出结果为:
```
Substring found at position 7
```
如果子字符串不存在于字符串中,find() 方法会返回 string::npos。需要注意的是,string::npos 是一个特殊的常量,它的值等于 string 类型的最大值,通常被用作查找失败的标志。
相关问题
std::string 查找子字符串
可以使用 std::string 的 find 函数来查找子字符串,示例代码如下:
```cpp
std::string str = "hello world";
std::string subStr = "world";
size_t pos = str.find(subStr);
if (pos != std::string::npos) {
std::cout << "子字符串在位置 " << pos << " 处" << std::endl;
} else {
std::cout << "未找到子字符串" << std::endl;
}
```
string替换子字符串代码
以下是一个使用 C++ 的示例代码,用于将字符串中的子字符串替换为另一个字符串:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello, world!";
string search_str = "world";
string replace_str = "everyone";
size_t pos = str.find(search_str);
if (pos != string::npos) {
str.replace(pos, search_str.length(), replace_str);
}
cout << str << endl;
return 0;
}
```
在这个示例代码中,我们首先定义了一个字符串 `str`,其中包含子字符串 `"world"`。然后,我们定义了要查找的子字符串 `search_str`,以及要替换为的字符串 `replace_str`。
接下来,我们使用 `find` 函数查找 `search_str` 在 `str` 中的位置。如果找到了,我们使用 `replace` 函数将其替换为 `replace_str`。
最后,我们输出替换后的字符串 `str`。