21xrx.com
2024-09-20 01:13:04 Friday
登录
文章检索 我的文章 写文章
C++字符串操作:使用string的头函数
2023-06-30 06:01:26 深夜i     --     --
C++ 字符串操作 string 头函数 编程

在C++中操作字符串是非常常见的一个任务。为了方便地操作字符串,C++提供了一个非常有用的类——字符串类(string),它定义在头文件 中。 string类的用法类似于char[],但它提供了更多的便利性和安全性。

string类提供了一系列的成员函数,可以让我们更加方便地对字符串进行操作。其中的头函数特别有用,下面我们来详细了解一下。

1. size()/length()

这两个函数都返回当前字符串的长度。

注意:size()和length()是完全相同的函数,你可以使用其中任何一个,按照个人喜好即可。

string str = "Hello, world!";

cout << "Length of str: " << str.size() << endl; // Length of str: 13

cout << "Length of str: " << str.length() << endl; // Length of str: 13

2. empty()

如果当前字符串为空字符串,empty()将返回true,否则返回false。

string str1 = "Hello, world!";

string str2 = "";

cout << str1.empty() << endl; // False

cout << str2.empty() << endl; // True

3. at()

at()函数接收一个参数n,返回第n个字符的引用,如果n越界将引发异常。

string str = "Hello, world!";

cout << str.at(0) << endl; // H

try{

  cout << str.at(20);

}catch(const std::out_of_range& oor)

  cout << "Out of range" << endl; // Out of range

4. front()

front()返回字符串中的第一个字符的引用。

string str = "Hello, world!";

cout << str.front() << endl; // H

5. back()

back()返回字符串中的最后一个字符的引用。

string str = "Hello, world!";

cout << str.back() << endl; // !

6. push_back()

push_back()函数用于在字符串的最后添加一个字符。

string str = "Hello, world!";

str.push_back(',');

str.push_back(' ');

str.push_back('I');

str.push_back('t');

cout << str << endl; // Hello, world! It

7. clear()

清除字符串的所有内容。

string str = "Hello, world!";

str.clear();

cout << str.length() << endl; // 0

使用string类的头函数可以让我们更加方便地对字符串进行操作,这样就不必使用C语言中的字符串操作函数,如strlen()、strcpy()等。

  
  

评论区

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