C++中字符串string类型中的各种常用函数
函数名 | 描述 | 调用方式 | 示例 |
---|---|---|---|
length() | 返回字符串的长度(即其中字符的个数) | string str = "Hello, World!"; int len = str.length(); | len的值为13 |
size() | 返回字符串的大小(即其中字节数,一般等于长度乘以每个字符所占的字节数) | string str = "Hello, World!"; int size = str.size(); | size的值为13(假设每个字符占用1个字节) |
empty() | 判断字符串是否为空,如果为空则返回true,否则返回false | string str = ""; bool isEmpty = str.empty(); | isEmpty的值为true |
clear() | 清空字符串 | string str = "Hello, World!"; str.clear(); | str的值变为空字符串 |
append() | 将一个字符串或字符添加到另一个字符串的末尾 | string str1 = "Hello, "; string str2 = "World!"; str1.append(str2); | str1的值变为"Hello, World!" |
assign() | 将一个字符串或字符赋值给另一个字符串 | string str1 = "Hello, "; string str2 = "World!"; str1.assign(str2); | str1的值变为"World!" |
insert() | 在指定位置插入一个字符串或字符 | string str ="Hello,World!"; str.insert(7, "my "); | str的值变为"Hello, my World!" |
erase() | 删除字符串中的一部分字符 | string str ="Hello,World!"; str.erase(7, 3); | str的值变为"Hello, !" |
replace() | 替换字符串中的一部分字符 | string str ="Hello,World!"; str.replace(7, 5, "my"); | str的值变为"Hello, my!" |
find() | 在字符串中查找指定的子字符串,并返回其起始位置的下标 | string str ="Hello,World!"; int pos = str.find("World"); | pos的值为7 |
rfind() | 在字符串中查找指定的子字符串,并返回其最后一次出现的位置的下标 | string str ="Hello,World!"; int pos = str.rfind("l"); | pos的值为10 |
substr() | 返回从指定位置开始的指定长度的子字符串 | string str = "Hello,World!"; string sub=str.substr(7, 5); | sub的值为"World" |
C++中的字符串string类型的操作符及使用方法:
操作符 | 描述 | 示例 |
---|---|---|
+ | 将两个字符串连接起来 | string str1 = "Hello,"; string str2 = " world!"; string str3 = str1 + str2; // "Hello, world!" |
= | 将一个字符串赋值给另一个字符串 | string str1 = "Hello,"; string str2 = " world!"; str2 = str1; // str2 = "Hello," |
== | 比较两个字符串是否相等 | string str1 = "Hello,"; string str2 = " world!"; if (str1 == "Hello,") // true |
!= | 比较两个字符串是否不相等 | string str1 = "Hello,"; string str2 = " world!"; if (str1 != str2) // true |
< | 比较两个字符串的字典序,左边小于右边 | string str1 = "apple"; string str2 = "banana"; if (str1 < str2) // true |
<= | 比较两个字符串的字典序,左边小于等于右边 | string str1 = "apple"; string str2 = "banana"; if (str1 <= str2) // true |
> | 比较两个字符串的字典序,左边大于右边 | string str1 = "apple"; string str2 = "banana"; if (str2 > str1) // true |
>= | 比较两个字符串的字典序,左边大于等于右边 | string str1 = "apple"; string str2 = "banana"; if (str2 >= str1) // true |
需要注意的是,C++中的字符串类型是以类的形式实现的,因此可以使用操作符重载的方式进行操作。此外,使用字符串类型时,需要包含头文件<string>。
