我是靠谱客的博主 稳重香菇,这篇文章主要介绍详解C++字符串常用操作函数(查找、插入、截取、删除等),现在分享给大家,希望可以做个参考。

1. 字符串查找函数

1.1 find 函数

原型为:unsigned int find(const basic_string &str) const;

作用:查找并返回str在本串中第一次出现的位置,位置从0开始

例子如下:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream> using namespace std; int main() { string str = "i love china. china love me"; string find_str = "love"; cout << str.find(find_str); // 2 return 0; }

2. 字符串插入函数

 2.1 append

  • 函数原型为:string append(const char* s) ;
  • 作用:将字符串s添加到本串尾,改变本串
  • 例子如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> using namespace std; int main() { string str = "i love china. "; char append_str[] = "china love me"; cout << str.append(append_str) << endl; // i love china. china love me cout << str << endl; // i love china. china love me return 0; }

2.2 insert

  • 函数原型为:string & insert(unsigned int p0, const char * s);
  • 作用:将s所指向的字符串插入在本串中位置p0之前,改变本串
  • 例子如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> using namespace std; int main() { string str = "i love . china love me"; char insert_str[] = "china"; cout << str.insert(7, insert_str) << endl; // i love china. china love me cout << str << endl; // i love china. china love me return 0; }

3. 字符串截取函数

3.1 substr

  • 函数原型为:string substr(unsigned int pos, unsigned int n) const;
  • 作用:取子串,取本串中位置pos开始的n个字符,构成新的string类对象作为返回值
  • 例子如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream> using namespace std; int main() { string str = "i love china. china love me"; cout << str.substr(2, 22) << endl; // love china. china love return 0; }

4. 字符串删除函数

 4.1 函数

  • 原型1为:string & erase(unsigned int pos);
  • 作用1:删除本串pos位置及之后的所有字符,改变本串
  • 函数原型2为:string & erase(unsigned int pos, unsigned int n);
  • 作用2:删除本串pos位置及之后的共n个字符,改变本串
  • 例子如下:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream> using namespace std; int main() { string str1 = "i love china. china love me"; cout << str1.erase(12) << endl; // i love china cout << str1 << endl; // i love china string str2 = "i love china. china love me"; cout << str2.erase(7, 18) << endl; // i love me cout << str2 << endl; // i love me return 0; }

到此这篇关于C++字符串常用操作函数(查找、插入、截取、删除等)的文章就介绍到这了,更多相关C++字符串操作函数内容请搜索靠谱客以前的文章或继续浏览下面的相关文章希望大家以后多多支持靠谱客!

最后

以上就是稳重香菇最近收集整理的关于详解C++字符串常用操作函数(查找、插入、截取、删除等)的全部内容,更多相关详解C++字符串常用操作函数(查找、插入、截取、删除等)内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(104)

评论列表共有 0 条评论

立即
投稿
返回
顶部