21xrx.com
2024-09-20 00:19:17 Friday
登录
文章检索 我的文章 写文章
C++中的字符串(string)
2023-07-01 22:58:55 深夜i     --     --
字符串 C++ std::string 字符串操作 字符串转换

C++作为一门高级编程语言,提供了丰富的数据结构和数据类型,其中字符串(string)也是不可或缺的一部分。在C++中,字符串可以使用string类来表示。它是由标准库提供的一个模板类,因此可以适用于各种字符串操作。

string类可以直接使用字符串常量赋值,例如:


#include <string>

#include <iostream>

using namespace std;

int main()

world!";

  cout << s1 << endl;

  return 0;

输出结果:


Hello, world!

除此之外,string类还支持多种字符串操作,如访问、修改、连接、比较、查找、分割、替换等。下面是一些常见的操作示例:

1. 访问和修改:


string s2 = "Goodbye!";

cout << s2[0] << endl; // G

s2[0] = 'g';

cout << s2 << endl; // goodbye!

2. 连接:


string s3 = "Hello,";

string s4 = " world!";

string s5 = s3 + s4;

cout << s5 << endl; // Hello, world!

3. 比较:


string s6 = "hello";

string s7 = "Hello";

if(s6 == s7)

  cout << "s6 = s7" << endl;

else

  cout << "s6 != s7" << endl;

// s6 != s7(区分大小写)

4. 查找:


string s8 = "Today is a sunny day!";

int pos = s8.find("sunny");

if(pos != -1)

  cout << "Find the \"sunny\" at position " << pos << endl;

else

  cout << "Not found!" << endl;

// Find the "sunny" at position 11

5. 分割:


string s9 = "apple,banana,orange";

int pos1 = s9.find(",");

int pos2 = 0;

while(pos1 != -1)

{

  cout << s9.substr(pos2, pos1 - pos2) << endl;

  pos2 = pos1 + 1;

  pos1 = s9.find(",", pos2);

}

cout << s9.substr(pos2, s9.length() - pos2) << endl;

/*

apple

banana

orange

*/

6. 替换:


string s10 = "She sells sea shells on the sea shore.";

int pos3 = s10.find("sea");

while(pos3 != -1)

{

  s10.replace(pos3, 3, "beach");

  pos3 = s10.find("sea", pos3 + 1);

}

cout << s10 << endl;

// She sells beach shells on the beach shore.

总的来说,string类为C++字符串操作提供了很多方便的方法,使得我们可以更加方便地处理字符串。在编写C++程序时,熟悉string类的使用是非常必要的。

  
  

评论区

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