21xrx.com
2024-09-20 00:03:45 Friday
登录
文章检索 我的文章 写文章
C++中string函数的用法
2023-07-06 13:24:04 深夜i     --     --
C++ string函数 用法

C++中的string是一个非常常见的数据类型。它可以用来存储任意长度的字符串,并支持多种操作。以下是一些常见的string函数及其用法:

1. length()函数:

length()函数返回一个字符串的长度。例如:


string str = "Hello, world!";

int len = str.length();

cout << "Length of string: " << len << endl;

输出:


Length of string: 13

2. substr()函数:

substr()函数可以用来截取一个字符串的子串,并返回一个新的字符串。它接受两个参数,第一个参数是起始位置(从0开始),第二个参数是子串的长度。例如:


string str = "Hello, world!";

string sub = str.substr(7, 5);

cout << "Substring: " << sub << endl;

输出:


Substring: world

3. find()函数:

find()函数可以用来搜索一个字符串中是否包含指定的子串。它返回子串的起始位置(从0开始),如果找不到则返回一个特殊的值string::npos。例如:


string str = "Hello, world!";

int pos = str.find("world");

if (pos != string::npos)

  cout << "Substring found at position " << pos << endl;

else

  cout << "Substring not found" << endl;

输出:


Substring found at position 7

4. replace()函数:

replace()函数可以用来替换一个字符串中指定的子串。它接受三个参数,第一个参数是替换开始位置(从0开始),第二个参数是替换长度,第三个参数是替换后的字符串。例如:


string str = "Hello, world!";

str.replace(7, 5, "everyone");

cout << "New string: " << str << endl;

输出:


New string: Hello, everyone!

除了以上这些函数,string还支持很多其他的操作,包括增加、删除、比较、连接等。对于想要深入学习string的同学,可以参考C++的官方文档:https://www.cplusplus.com/reference/string/string/

  
  

评论区

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