C++中的标准库<string>
提供了一系列用于操作字符串的常用函数。下面列举了一些常见的字符串操作函数:
length()
或size()
: 返回字符串的长度。empty()
: 判断字符串是否为空。clear()
: 清空字符串内容。substr(pos, len)
: 返回从指定位置开始的指定长度子串。append(str)
: 在字符串末尾追加指定字符串。insert(pos, str)
: 在指定位置插入字符串。erase(pos, len)
: 删除从指定位置开始的指定长度字符。replace(pos, len, str)
: 用指定字符串替换从指定位置开始的指定长度字符。find(str)
: 查找指定字符串在当前字符串中的第一个出现位置。rfind(str)
: 查找指定字符串在当前字符串中的最后一个出现位置。substr(pos, len)
: 返回从指定位置开始的指定长度子串。compare(str,pos,len)
: 比较字符串与指定字符串的大小关系。#include <iostream> #include <string> int main() { std::string str = "Hello, World!"; std::cout << "字符串长度: " << str.length() << std::endl; std::cout << "字符串是否为空: " << (str.empty() ? "是" : "否") << std::endl; str.clear(); std::cout << "清空后的字符串: " << str << std::endl; str = "Hello, World!"; std::string sub = str.substr(7, 5); std::cout << "子串: " << sub << std::endl; str.append(" How are you?"); std::cout << "追加后的字符串: " << str << std::endl; str.insert(12, " my friend"); std::cout << "插入后的字符串: " << str << std::endl; str.erase(0, 6); std::cout << "删除后的字符串: " << str << std::endl; str.replace(7, 5, "World"); std::cout << "替换后的字符串: " << str << std::endl; int pos = str.find("World"); std::cout << "查找位置: " << pos << std::endl; return 0; }
#include <iostream> #include <string> int main() { std::string str1 = "Hello"; std::string str2 = "Hellp"; int n = 4; int result = str1.compare(0, n, str2, 0, n); if (result == 0) { std::cout << "前" << n << "项相等" << std::endl; } else if (result < 0) { std::cout << "str1排在str2前面" << std::endl; } else { std::cout << "str1排在str2后面" << std::endl; } return 0; }