【C/C++】基础知识之string字符串

简介: 【C/C++】基础知识之string字符串

在C/C++中,string是一种常用的字符串类型,其实现是一个类。使用string可以方便地进行字符串的操作。

下面是string的一些基本操作:

创建string对象:可以通过以下方式来创建string对象:

string str1; string str2 = "Hello World"; string str3("I am a string");

获取string对象的长度:可以使用size()或者length()方法来获取string对象中字符的数量。

string str = "Test String"; int len = str.size(); // 等同于 str.length();
cout << "String Length: " << len << endl;

连接字符串:可以使用+号来将两个string对象连接起来,或者使用append()方法来追加一个string对象到另一个对象的末尾。

string str1 = "Hello"; string str2 = "World"; string str3 = str1 + " " + str2; cout << "str3: " << str3 << endl;

string str = "Hello"; str.append(" World"); cout << "str: " << str << endl;

查找字符串:可以使用find()方法来查找string对象中是否包含一个子串,如果找到了则返回子串的首字符所在的索引;如果没有找到则返回string::npos。

string str = "Today is a good day"; int pos = str.find("good"); if (pos != string::npos) { cout << "'good' is at position " << pos << endl; } else { cout << "'good' is not found" << endl; }

截取字符串:可以使用substr()方法来截取一个string对象的子串,参数为起始索引和截取长度。

string str = "Today is a good day"; string sub = str.substr(9, 4); // 从第9个字符开始截取4个字符 cout << "sub: " << sub << endl;

删除字符串:可以使用erase()方法来删除string对象中的一个子串,参数为起始索引和删除长度。

string str = "Today is a good day"; str.erase(9, 4); // 删除从第9个字符开始的4个字符 cout << "str: " << str << endl;

替换字符串:可以使用replace()方法来替换string对象中的一个子串,参数为起始索引、替换长度和替换字符串。

string str = "Today is a good day"; str.replace(9, 4, "a bad"); cout << "str: " << str << endl;

以上是string的一些基本操作,使用string可以让字符串的操作更加方便。

相关文章
|
26天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
211 100
|
26天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
273 99
|
29天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
29天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
2月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
223 92
|
3月前
|
C语言 C++
【实战指南】 C/C++ 枚举转字符串实现
本文介绍了在C/C++中实现枚举转字符串的实用技巧,通过宏定义与统一管理枚举名,提升代码调试效率并减少维护错误。
274 56
|
3月前
|
自然语言处理 Java Apache
在Java中将String字符串转换为算术表达式并计算
具体的实现逻辑需要填写在 `Tokenizer`和 `ExpressionParser`类中,这里只提供了大概的框架。在实际实现时 `Tokenizer`应该提供分词逻辑,把输入的字符串转换成Token序列。而 `ExpressionParser`应当通过递归下降的方式依次解析
253 14
|
8月前
|
存储 安全 C语言
C++ String揭秘:写高效代码的关键
在C++编程中,字符串操作是不可避免的一部分。从简单的字符串拼接到复杂的文本处理,C++的string类为开发者提供了一种更高效、灵活且安全的方式来管理和操作字符串。本文将从基础操作入手,逐步揭开C++ string类的奥秘,帮助你深入理解其内部机制,并学会如何在实际开发中充分发挥其性能和优势。