c++字符串find,replace,删除 c加加代码举例子
时间: 2023-06-05 20:08:26 浏览: 140
以下是一个使用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语言中的字符串查找函数为strstr,而不是find函数。此函数用于在一个字符串中查找另一个指定的字符串,并返回第一次出现的位置,如果没有找到则返回NULL。函数原型为: char *strstr(const char *str1, const char *str2);
c++字符串全局替换特定字符串实现代码
以下是 C 语言实现字符串全局替换特定字符串的代码:
```c
#include <stdio.h>
#include <string.h>
void replace(char *str, char *old, char *new) {
char buffer[1024];
char *p;
while ((p = strstr(str, old)) != NULL) {
strncpy(buffer, str, p - str);
buffer[p - str] = '\0';
strcat(buffer, new);
strcat(buffer, p + strlen(old));
strcpy(str, buffer);
}
}
int main() {
char str[] = "hello world, hello CSDN!";
char old[] = "hello";
char new[] = "hi";
replace(str, old, new);
printf("%s\n", str);
return 0;
}
```
以上代码可以将字符串中所有的特定字符串替换为新的字符串。
阅读全文
相关推荐














