C++ 字符串(string)使用

在C++中,字符串(String)是表示文本数据的关键组成部分。C++标准库提供了std::string类,它是处理字符串的首选方式,相较于传统的C风格字符串(字符数组),std::string提供了更多的功能、更高的安全性和便捷性。

字符串定义和初始化

cpp 复制代码
string str="Hello world!";
cpp 复制代码
string str("Hello world");

拼接字符串

cpp 复制代码
string str1="Hello";
string str2=" world!";
str1 = str1 + str2;    //Hello world!

访问与修改字符串中的字符

cpp 复制代码
string str = "Hello World!";
str[6] = 'w';// 将'W'改为小写'w'

提取子字符串

cpp 复制代码
string str = "Hello World!";
str = str.substr(0,5);// 从索引0开始提取5个字符

查找子字符串

cpp 复制代码
string str = "Hello World!";
size_t pos = str.find("llo");// 查找"llo"的位置,返回索引2

字符串比较

C++中的字符串比较默认是按照字典序进行比较,也就是比较字符串的ASCII码值。

使用运算符比较
cpp 复制代码
    string str1 = "abc";
    string str2 = "abc";
    bool b = str1 > str2;
    b = str1 < str2;
    b = str1 == str2;
使用compare函数比较
cpp 复制代码
 string s1 = "babc";
 string s2 = "bcabc";
 int n = s1.compare(s2); //s1和s2比较

返回值:

如果s1和s2相等,compare()返回 0。

如果s1大于s2,compare()返回 1。

如果s1小于s2,compare()返回 -1。

获取字符串长度

使用成员方法size、length

cpp 复制代码
string s1 = "babca";
cout << s1.size() << endl;
cout << s1.length() << endl;

字符串转大小写

使用的是 transform 函数配合 ::toupper 或 ::tolower 函数来完成这个任务。

cpp 复制代码
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    string s1 = "bABca";
    transform(s1.begin(), s1.end(), s1.begin(), ::toupper); //转大写
    transform(s1.begin(), s1.end(), s1.begin(), ::tolower); //转小写
    cout << s1;
}
  • #include <algorithm>:用于 transform 函数。
  • transform 函数接受四个参数:输入范围的起始迭代器、输入范围的结束迭代器、输出范围的起始迭代器、以及一个用于转换每个元素的函数。
相关推荐
clint4561 天前
C++进阶(1)——前景提要
c++
夜悊1 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴1 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0012 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾2 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you2 天前
constexpr函数
c++
凡人叶枫2 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫2 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss2 天前
BRpc使用
c++·rpc
-森屿安年-2 天前
63. 不同路径 II
c++·算法·动态规划