当前位置:首页 C++ > 正文

c++string类函数

作者:野牛程序员:2023-06-06 19:57:46 C++阅读 2704

C++中的std::string类提供了许多成员函数来处理字符串。以下是一些常用的函数:

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

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

std::string str = "Hello";
bool isEmpty = str.empty();
  1. clear(): 清空字符串内容。

std::string str = "Hello";
str.clear();
  1. append(): 将字符串添加到当前字符串的末尾。

std::string str = "Hello";
str.append(" World");// 现在 str 的值为 "Hello World"
  1. insert(): 在指定位置插入字符串。

std::string str = "Hello";
str.insert(5, " World");// 现在 str 的值为 "Hello World"
  1. erase(): 从指定位置开始删除指定数量的字符。

std::string str = "Hello World";
str.erase(5, 6);// 现在 str 的值为 "Hello"
  1. substr(): 提取子字符串。

std::string str = "Hello World";
std::string sub = str.substr(6, 5);// sub 的值为 "World"
  1. find(): 查找子字符串的位置。

std::string str = "Hello World";
size_t pos = str.find("World");// pos 的值为 6

这只是std::string类的一小部分函数,还有许多其他有用的函数可供使用。


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

最新推荐

热门点击