21xrx.com
2024-06-02 22:44:55 Sunday
登录
文章检索 我的文章 写文章
C++中string类型的常用方法
2023-06-30 00:30:30 深夜i     --     --
C++ string类型 常用方法

C++语言中的string类型是常见的字符串类型,它相比于char*类型在字符串操作上更为方便,同时也消除了char*类型可能出现的指针问题。那么,在C++中string类型有哪些常用方法呢?

1. length()方法

该方法用于返回当前string类型存储的字符串的长度。例如:

string str = "hello";

int len = str.length(); // len为5

2. size()方法

该方法与length()方法用法相同,用于返回当前string类型存储的字符串的长度。

3. empty()方法

该方法用于判断当前string类型存储的字符串是否为空。当字符串为空时返回true,否则返回false。例如:

string str = "";

if (str.empty())

  cout << "string is empty" << endl;

else

  cout << "string is not empty" << endl;

4. clear()方法

该方法用于清空string类型存储的字符串。例如:

string str = "hello";

str.clear(); // 清空字符串

5. substr()方法

该方法用于从当前string类型存储的字符串中提取指定位置和长度的子串。例如:

string str = "hello world";

string sub = str.substr(0, 5); // sub为"hello"

6. append()方法

该方法用于在当前string类型存储的字符串末尾添加指定字符串。例如:

string str = "hello";

str.append(" world"); // str为"hello world"

7. replace()方法

该方法用于将当前string类型存储的字符串中指定位置和长度的子串替换成指定字符串。例如:

string str = "hello world";

str.replace(6, 5, ", there"); // str为"hello, there"

8. c_str()方法

该方法用于将当前string类型存储的字符串转换成以'\0'结尾的字符数组。例如:

string str = "hello";

const char* cstr = str.c_str(); // cstr为"hello\0"

总之,C++中的string类型拥有多种常用方法,可以方便地对字符串进行各种操作。程序员们可以根据实际需要选择合适的方法来处理字符串。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复