21xrx.com
2024-05-20 06:18:06 Monday
登录
文章检索 我的文章 写文章
C++字符串删除操作
2023-07-13 08:05:34 深夜i     --     --
C++ 字符串 删除操作 erase substr

在C++中,字符串是一种非常常见的数据类型。在实际的编程过程中,我们经常需要对字符串进行删除操作。本文将为大家介绍一些常用的C++字符串删除操作。

1. erase()函数

erase()函数是C++ STL中的一个函数,可以用于从字符串中删除一个或多个字符。其语法如下:

string.erase(position,length)

其中,position表示要删除的字符的位置,length表示要删除的字符的数量。

示例代码:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str = "Hello World!";

  str.erase(5, 3);  //删除World

  cout << str << endl;  //输出Hello!

 

  return 0;

}

2. substr()函数

substr()函数可以用于从字符串中提取一部分子串,同时也可以用于删除子串。其语法如下:

string.substr(position,length)

其中,position表示子串的起始位置,length表示子串的长度。如果省略length,则默认提取从position开始到字符串的末尾的所有字符。

示例代码:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str = "Hello World!";

  str = str.substr(0, 5);  //删除World

  cout << str << endl;  //输出Hello

 

  return 0;

}

3. replace()函数

replace()函数可以用于替换字符串中的某一部分。其语法如下:

string.replace(position,length,new_string)

其中,position表示要替换的起始位置,length表示要替换的部分的长度,new_string表示用于替换原字符串的新字符串。

示例代码:


#include <iostream>

#include <string>

using namespace std;

int main() {

  string str = "Hello World!";

  str.replace(0, 5, "Hi");  //用Hi替换Hello

  cout << str << endl;  //输出Hi World!

 

  return 0;

}

通过上述的介绍,我们可以看到C++字符串删除操作主要是通过erase()函数、substr()函数和replace()函数实现的。掌握了这些函数的使用方法,我们就可以轻松地对字符串进行删除操作,提高程序的效率。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复