【C++标准头文件】<string>

函数 说明
c_str 将 string 转换为 char*(与C风格的字符串不同,string 的结尾没有结束标志’\0’)
length / size 获取字符串长度(size是为了和其他容器接口一致)
+ / append 字符串拼接
insert 指定位置插入字符/字符串
find 查找子字符串
substr 获取子字符串
empty 判断是否为空字符串
[] / at 访问指定位置的字符
stoi / stol / stoll 【C++ 11】转换字符串为有符号 int / long / long long
stoul / stoull 【C++ 11】转换字符串为无符号 long / long long
stof / stod 【C++ 11】转换字符串为 float / double
to_string 【C++ 11】转换整数或浮点值为 string

c_str

string title = "Happy NewYear 2023!";
 
const char *titleCharArray = title.c_str();

length、size

string title = "Happy NewYear 2023!";

//size = 19
unsigned int size = title.size();
//length = 19
unsigned int length = title.length();

append

string hello = "hello";
string newYear = "2023";

//hello2023
string sample1 = hello + "2023";
//hello2023
string sample2 = hello + newYear;

//hello2023
string sample3 = hello.append("2023");
//hello20232023,因为 append 会修改原始字符串,相当于 +=
string sample4 = hello.append(newYear);

insert

string sample5 = "ABCGH";

//sample5 = ABCDEFGH
sample5.insert(3, "DEF");

find

string sample6 = "ABCDEFGH";

//result = 3
unsigned int result1 = sample6.find("DEF");
//result = -1
unsigned int result2 = sample6.find("EDC");
//result = -1
unsigned int result3 = sample6.find("JH");

substr

string sample7 = "ABCDEFGH";

//result = CDE
string result = sample7.substr(2, 3);

empty

string sample8;

//result1 = 1
bool result1 = sample8.empty();

sample8 = "ABCDEFG";
//result2 = 0
bool result2 = sample8.empty();

at

string sample9 = "ABCDEFGH";

//result1 = E
char result1 = sample9.at(4);
//result2 = E
char result2 = sample9[4];

stoi

string sample10 = "100";

int result = stoi(sample10);

to_string

int sample11 = 100;

string result = to_string(sample11);

你可能感兴趣的:(#,标准头文件,c++,c语言,unix,linux)