c++字符串find,replace,删除 c加加代码举例子
时间: 2023-06-05 13:08:26 浏览: 63
以下是一个使用C++字符串的find、replace和删除操作的示例代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str = "Hello World!";
// 查找子字符串
size_t pos = str.find("World"); // 返回值为子字符串在原字符串中的位置
if (pos != string::npos)
{
cout << "子字符串 'World' 在原字符串中的位置:" << pos << endl;
}
// 替换子字符串
string new_str = "C++";
str.replace(pos, 5, new_str); // 5表示需要替换的字符个数
cout << "替换后的字符串为:" << str << endl;
// 删除字符
str.erase(0, 6); // 删除原字符串中前6个字符
cout << "删除前6个字符后的字符串为:" << str << endl;
return 0;
}
```
输出结果为:
```
子字符串 'World' 在原字符串中的位置:6
替换后的字符串为:Hello C++!
删除前6个字符后的字符串为:C++!
```
相关问题
c++ 字符串find函数
C++中的字符串类(std::string)提供了find()函数,可以用于查找一个子串在字符串中出现的位置。它的语法如下:
```cpp
size_t find(const string& str, size_t pos = 0) const;
size_t find(const char* s, size_t pos = 0) const;
size_t find(const char* s, size_t pos, size_t n) const;
size_t find(char c, size_t pos = 0) const;
```
其中,第一个参数是要查找的子串,第二个参数是起始查找位置,默认为0。
示例:
```cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "hello world";
int pos = str.find("world");
if (pos != string::npos) {
cout << "子串 \"world\" 在字符串 \"" << str << "\" 中的位置为:" << pos << endl;
} else {
cout << "子串 \"world\" 未找到!" << endl;
}
return 0;
}
```
输出结果:
```
子串 "world" 在字符串 "hello world" 中的位置为:6
```
c++字符串find函数
C语言中的字符串查找函数为strstr,而不是find函数。此函数用于在一个字符串中查找另一个指定的字符串,并返回第一次出现的位置,如果没有找到则返回NULL。函数原型为: char *strstr(const char *str1, const char *str2);