当前位置:首页C++程序设计 > 正文

c++ string类的常用方法

作者:野牛程序员:2023-06-13 14:38:22C++程序设计阅读 2827

C++ 的字符串类 std::string 提供了许多常用的方法来操作和处理字符串。以下是一些 std::string 的常用方法:

  1. length()size(): 返回字符串的长度。

std::string str = "Hello, world!";
int length = str.length();  // 或者使用 str.size();
  1. empty(): 检查字符串是否为空。

std::string str = "Hello";
if (str.empty()) {    
// 字符串为空
}
  1. clear(): 清空字符串内容。

std::string str = "Hello";
str.clear();  // 清空字符串,str 现在是空字符串
  1. append(): 在字符串末尾追加字符、字符串或其他 std::string

std::string str = "Hello";
str.append(" world!");  // 在字符串末尾追加字符串
str.append(1, '!');    // 在字符串末尾追加字符 '!'
  1. insert(): 在指定位置插入字符、字符串或其他 std::string

std::string str = "Hello";
str.insert(5, " world!");  // 在位置 5 插入字符串
  1. erase(): 删除指定位置的字符或一段子字符串。

std::string str = "Hello, world!";
str.erase(5, 7);  // 删除从位置 5 开始的 7 个字符,结果为 "Hello!"
  1. substr(): 提取子字符串。

std::string str = "Hello, world!";
std::string sub = str.substr(7, 5);  // 从位置 7 开始提取 5 个字符,结果为 "world"
  1. replace(): 替换指定位置的字符或一段子字符串。

std::string str = "Hello, world!";
str.replace(7, 5, "Earth");  // 在位置 7 替换 5 个字符为 "Earth",结果为 "Hello, Earth!"
  1. find(): 查找子字符串第一次出现的位置。

std::string str = "Hello, world!";
size_t pos = str.find("world");  // 查找子字符串 "world" 的位置,结果为 7
  1. rfind(): 从末尾开始查找子字符串第一次出现的位置。

std::string str = "Hello, world!";
size_t pos = str.rfind("o");  // 从末尾开始查找字符 'o' 的位置,结果为 8

这些只是 std::string 类的一些常用方法,还有许多其他方法可用于字符串的处理和操作。


在 C++ 中,字符串的位置编号是从 0 开始的。这意味着字符串的第一个字符的位置是 0,第二个字符的位置是 1,以此类推。例如,对于字符串 "Hello",位置编号如下:

+---+---+---+---+---+
| H | e | l | l | o |
+---+---+---+---+---+
  0   1   2   3   4

请注意,这适用于 std::string 类及其他与字符串索引相关的 C++ 容器和操作。

野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击