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 函数接受四个参数:输入范围的起始迭代器、输入范围的结束迭代器、输出范围的起始迭代器、以及一个用于转换每个元素的函数。
相关推荐
qq_479875432 小时前
C++ 网络编程中的 Protobuf 消息分发 (Dispatcher) 设计模式
网络·c++·设计模式
Tandy12356_2 小时前
手写TCP/IP协议——IP层输出处理
c语言·网络·c++·tcp/ip·计算机网络
博语小屋2 小时前
实现简单日志
linux·服务器·数据库·c++
ZouZou老师8 小时前
C++设计模式之装饰器模式:以家具生产为例
c++·设计模式·装饰器模式
ZouZou老师8 小时前
C++设计模式之桥接模式:以家具生产为例
c++·设计模式·桥接模式
呱呱巨基8 小时前
Linux 进程概念
linux·c++·笔记·学习
liulilittle9 小时前
C++ 浮点数封装。
linux·服务器·开发语言·前端·网络·数据库·c++
ZouZou老师9 小时前
C++设计模式之组合模式:以家具生产为例
c++·设计模式·组合模式
yong15858553439 小时前
2. Linux C++ muduo 库学习——原子变量操作头文件
linux·c++·学习
小小8程序员9 小时前
STL 库(C++ Standard Template Library)全面介绍
java·开发语言·c++