String类函数复习
请注意,本文内容主要参考以下博客内容:
C++中的string类用法简介
【C++】STL常用容器总结之十二:string类
C++文档
C++中的String类
String转换为Char*
string str = "Hello World!";
const char* ch = str.c_str();
cout 可直接输出string字符串内容;
const char*;
string对象一旦初始化就不可变。
char*、char[]转换为string
const char* ch_ptr = "hello";
char ch[] = "world";
string str_chptr;
string str_ch;
str_chptr = ch_ptr;
str_ch = ch; //直接赋首地址
int转换为string
int num = 1024;
string str;
str = to_string(num);
计算String长度
string str = "Hello World!";
int str_length = str.length();
String字符串比较
string str = "Hello World!";
int str_length = str.length();
string cmp = "Hello World";
int result = str.compare(cmp); // 'result = 0' means str is equal to cmp.
String对象判空
if (str2.empty())
cout << "str2 is empty." << endl;
String类的find方法
用于判定子字符串是否存在,返回下标(int)。
string a = "hello world";
string b = "hello";
size_t index = a.find(b);
if(index != string::npos) //npos表示子串不在母串中
cout << index;
string s;
1) s.empty(); // s为空串 返回true
2) s.size(); // 返回s中字符个数 类型应为:string::size_type
3) s[n]; // 从0开始相当于下标访问
4) s1+s2; // 把s1和s2连接成新串 返回新串
5) s1=s2; // 把s1替换为s2的副本
6) v1==v2; // 比较,相等返回true
7) `!=, <, <=, >, >=` 惯有操作 任何一个大写字母都小于任意的小写字母
Assign
s.assign(str,1,3); // 如果str是"iamangel" 就是把"ama"赋给字符串
s.assign(str,2,string::npos); // 把字符串str从索引值2开始到结尾赋给s
拷贝
str1=str.substr(2) //提取子串,提取出 str 的 下标为2 到末尾,给 str1
str1=str.substr(2,3) //提取子串,提取出 str 的 下标为2 开始,提取三个字节,给 str1
插入字符
str.append("ABC") //在str末尾添加一个字符串 "ABC",参数必须是字符串形式
str.push_back('A')//在str末尾添加一个字符 'A' ,参数必须是字符形式
str.insert(2,3,'A') //在str下标为2的位置添加 3个 字符'A'
str.insert(2,"ABC") //在str下标为2的位置添加 字符串 "ABC"
str.insert(2,"ABC",1) //在str下标为2的位置添加 字符串 "ABC" 中 1个 字符
str.insert(2,"ABC",1,1) //在str下标为2的位置添加 字符串 "ABC" 中从位置 1 开始的 1 个字符
字符串删除
str.erase(2) //删除 下标2 的位置开始,之后的全删除
str.erase(2,1) //删除 下标2 的位置开始,之后的 1个 删除
str.clear() //删除 str 所有
交换字符串
str.swap(str1) //交换 str1 和 str 的字符串
替换字符串
str.replace(2,4,"abcd") //从 下标2 的位置,替换 4个字节 ,为"abcd"
字符串反转
reverse(str.begin(),str.end()) //str的开始 到 结束字符反转
统计字符出现个数
#include<algorithm>
string str = "hello";
int num = count(str.begin(),str.end(),'h');
------------------
有为,有守,有趣。
------------------