21xrx.com
2025-06-14 19:58:49 Saturday
文章检索 我的文章 写文章
C++中String类实现代码
2023-07-12 02:34:54 深夜i     29     0
C++ String类 实现代码

C++中的String类是一个非常常用的字符串类,它提供了许多实用的方法和操作符,使得字符串的操作变得更加简单和方便。下面是一些关于String类实现的代码示例。

1. 定义字符串变量

定义String对象的方式有很多种,例如:

string str1 = "hello";
string str2("world");
string str3 = str1 + str2;

2. 字符串长度

在C++中,可以使用`size()`或`length()`方法获取字符串的长度。例如:

string str = "hello";
int len = str.length();
cout << len << endl; // 输出5

3. 字符串比较

可以使用`compare()`方法比较两个字符串,例如:

string str1 = "hello";
string str2 = "world";
int result = str1.compare(str2);
if (result == 0)
  cout << "str1和str2相等" << endl;
else if (result < 0)
  cout << "str1小于str2" << endl;
else
  cout << "str1大于str2" << endl;

4. 截取字符串

使用`substr()`方法可以截取字符串,例如:

string str = "hello world";
string substr = str.substr(0, 5);
cout << substr << endl; // 输出"hello"

5. 查找字符串

可以使用`find()`方法查找一个子字符串在另一个字符串中的位置,例如:

string str = "hello world";
int pos = str.find("world");
cout << pos << endl; // 输出6

6. 替换字符串

使用`replace()`方法可以替换字符串中的指定部分,例如:

string str = "hello world";
str.replace(6, 5, "there");
cout << str << endl; // 输出"hello there"

7. 字符串拼接

可以使用`+`操作符或`append()`方法拼接字符串,例如:

string str1 = "hello";
string str2 = "world";
string str3 = str1 + " " + str2;
str3.append("!");
cout << str3 << endl; // 输出"hello world!"

以上是一些关于C++中String类实现的代码示例,String类在实际开发中非常常用,掌握这些操作可以让你更加高效地操作字符串。

  
  

评论区