21xrx.com
2025-04-01 14:05:40 Tuesday
文章检索 我的文章 写文章
C++字符串操作
2023-07-02 13:09:23 深夜i     9     0
C++ 字符串 操作

C++是一种功能强大的编程语言,它支持许多字符串操作。在C++中,字符串是由一系列字符组成的。下面让我们来了解一下C++中的字符串操作。

创建字符串:

在C++中,可以使用字符串字面量来创建一个字符串,例如:

string str = "Hello, World!";

还可以使用构造函数来创建字符串:

string str = string("Hello, World!");

字符串大小:

使用`size()`方法可以获取字符串的大小,

string str = "Hello, World!";
cout << str.size() << endl; //输出:13

字符串连接:

使用`+`运算符可以将两个字符串连接起来,

string str1 = "Hello, ";
string str2 = "World!";
string str = str1 + str2;
cout << str << endl; //输出:Hello, World!

字符串查找:

使用`find()`方法可以查找字符串中的某个子串,

string str = "Hello, World!";
int pos = str.find("World");
if (pos != string::npos)
  cout << "Substring found at position " << pos << endl; //输出:Substring found at position 7
else
  cout << "Substring not found" << endl;

字符串替换:

使用`replace()`方法可以将字符串中的某个子串替换成另一个子串,

string str = "Hello, World!";
str.replace(7, 5, "C++");
cout << str << endl; //输出:Hello, C++!

字符串截取:

使用`substr()`方法可以截取字符串的一段子串,

string str = "Hello, World!";
string sub = str.substr(7, 5);
cout << sub << endl; //输出:World

总之,C++中的字符串操作功能非常强大,这些操作可以大大方便我们在编写程序时的字符串处理工作。

  
  

评论区