山东智趣岛论坛
标题: C++字符串常用函数及功能 [打印本页]
作者: 王浩宇 时间: 2025-2-15 11:24
标题: C++字符串常用函数及功能
[size=16.002px]以下是C++中常用的字符串函数及其功能的表格,附带简单的案例说明:
函数名
功能描述
示例代码
length()
返回字符串的长度(字符数)string str = "Hello"; cout << str.length(); // 输出 5
size()
与 length() 功能相同,返回字符串的长度string str = "Hello"; cout << str.size(); // 输出 5
empty()
检查字符串是否为空,返回布尔值string str = ""; cout << str.empty(); // 输出 1 (true)
clear()
清空字符串内容string str = "Hello"; str.clear(); cout << str; // 输出空字符串
append()
在字符串末尾追加字符串或字符string str = "Hello"; str.append(" World"); cout << str; // 输出 "Hello World"
push_back()
在字符串末尾追加一个字符string str = "Hello"; str.push_back('!'); cout << str; // 输出 "Hello!"
insert()
在指定位置插入字符串或字符string str = "Hello"; str.insert(5, " World"); cout << str; // 输出 "Hello World"
erase()
删除字符串中的一部分string str = "Hello World"; str.erase(5, 6); cout << str; // 输出 "Hello"
replace()
替换字符串中的一部分string str = "Hello World"; str.replace(6, 5, "There"); cout << str; // 输出 "Hello There"
substr()
返回字符串的子串string str = "Hello World"; cout << str.substr(6, 5); // 输出 "World"
find()
查找子串或字符在字符串中首次出现的位置,返回索引string str = "Hello World"; cout << str.find("World"); // 输出 6
rfind()
查找子串或字符在字符串中最后一次出现的位置,返回索引string str = "Hello World"; cout << str.rfind('o'); // 输出 7
compare()
比较两个字符串,返回整数结果(0表示相等,负数表示小于,正数表示大于)string str1 = "Hello"; string str2 = "World"; cout << str1.compare(str2); // 输出负数
c_str()
返回一个指向以空字符结尾的字符数组的指针string str = "Hello"; const char* cstr = str.c_str(); cout << cstr; // 输出 "Hello"
at()
返回指定位置的字符,提供边界检查string str = "Hello"; cout << str.at(1); // 输出 'e'
operator[]
返回指定位置的字符,不提供边界检查string str = "Hello"; cout << str[1]; // 输出 'e'
swap()
交换两个字符串的内容string str1 = "Hello"; string str2 = "World"; str1.swap(str2); cout << str1; // 输出 "World"
assign()
将字符串内容替换为指定的字符串或字符string str = "Hello"; str.assign("World"); cout << str; // 输出 "World"
resize()
调整字符串的大小,可以截断或填充字符string str = "Hello"; str.resize(10, '!'); cout << str; // 输出 "Hello!!!!!"
copy()
将字符串的内容复制到字符数组中string str = "Hello"; char buffer[10]; str.copy(buffer, 5); buffer[5] = '\0'; cout << buffer; // 输出 "Hello"[size=16.002px]这些函数是C++标准库中std::string类的一部分,提供了丰富的字符串操作功能。
欢迎光临 山东智趣岛论坛 (https://abc.sdzqd.com/) |
Powered by Discuz! X3.3 |