- zouyc 的博客
字符串string类
- @ 2025-9-19 9:59:56
string类概述
string类是C++专有的,用于处理字符或者字符串的类,封装了很多方法,使用方便,推荐优先使用它。 使用它时,需要包含头文件。
string类完整代码
```cpp
/*
p_string.cpp v1.1.6 2025-4-18
---------------------------------------------------
分割:csplitstr
拼接:+,append
加单个字符:push_back
插入字符串:insert
长度:length,size
遍历:3种方法
查找:find
替换:replace
截取字符:substr
删除:erase
排序:sort
*/
#include <iostream> //
#include <string> //用string
#include <vector> //变长数组,向量
#include <algorithm> //算法,例如排序sort
//#include <bits/stdc++.h>
using namespace std;
//参数:s 字符串数字,空格隔开,例如:12 65 73 86 97
//返回:vector,元素是分割好的整数
vector<int> csplit(string s) {
const string SP=" ";
vector<int> v;
size_t found = s.find(SP);
int pos=0;
string value;
while (found!=string::npos) { //找到
value=s.substr(pos,found-pos);
v.push_back(stoi(value));
pos=found+SP.length();
found=s.find(SP,pos);
}
value=s.substr(pos); //pos在最后一位前面
v.push_back(stoi(value));
return v;
}
// s: 空格分开的字符串:I am a student
//返回:分割好的的vector,元素是单词
vector<string> csplitStr(string s) {
const string SP=" ";
vector<string> v;
size_t found = s.find(SP);
int pos=0;
string value;
while (found!=string::npos) { //找到
value=s.substr(pos,found-pos);
v.push_back(value);
pos=found+SP.length();
found=s.find(SP,pos);
}
value=s.substr(pos); //pos在最后一位前面
v.push_back(value);
return v;
}
// s: 按sc分开的字符串:I,am,a,student
// sc: 按指定字符分割,例如","
//返回:分割好的的vector,元素是单词
vector<string> csplitStr(string s,string sc) { //函数重载
const string SP=sc;
vector<string> v;
size_t found = s.find(SP);
int pos=0;
string value;
while (found!=string::npos) { //找到
value=s.substr(pos,found-pos);
v.push_back(value);
pos=found+SP.length();
found=s.find(SP,pos);
}
value=s.substr(pos); //pos在最后一位前面
v.push_back(value);
return v;
}
//字符串分割:函数版 C split string
//dst 保存数组
//n 有效个数
// hello world some any English Chinese America
void csplitstr(string dst[],int &n) { //&n 是引用传递
int i=0;
string str;
while(cin>>str) { //cin>>str有输入就是真
dst[i++]=str;
}
n=i;
}
// 删除空格,返回没有空格字符串
// inStr 输入的含有空格的字符串
// 返回 没有空格的字符串
string removeSpace(string src) {
size_t found=0;
while (true) {
found = src.find(" "); //查找单个空格
if (found!=string::npos) {
src.replace(found,1,""); //替换一个空格为空串
//1 表示被替换空格数量
}
else {
break;
}
}
return src;
}
bool cmp(char x,char y) { //x 数组前面的 y 数组后面的
return x>y; //> 降序; < 升序
}
int main() {
//string a; //定义,无初始化
/*// 定义、赋值与下标 // 索引、下标、编号
string a="Hello World"; // H -- 0
// e -- 1
// ...
// W -- 6
cout<<a;
//cout<<a[6]; */
/*//初始化
//string a("Hello"); //等效上者
string a(10,'u'); //重复10个u
cout<<a;*/
/*//char指针 -> string
const char *p="Hello World";
cout<<*p; //p指向H
p++; //指针往前走一步
cout<<"\n";
cout<<*p; //此时指向e
cout<<"\n";
string a(p); //ello World
cout<<a;*/
/*//char数组 -> string
char a[]="Hello World";
string s(a);
cout<<s;*/
/*//string -> c字符指针
string a="Hello World"; //c_str()函数返回一个指向C字符串的指针
const char *p =a.c_str();
printf("%s\n",p); //const char *c_str();*/
/*//cin遇到空格,就忽略
string a;
cin>>a;
cout<<a;*/
/*//带空格的整行输入 the great wall
string a;
getline(cin,a); //get line 得到一行
cout<<a;*/
/* 多行输入的例子
白日依山尽
黄河入海流
欲穷千里目
更上一层楼
*/
/*//读n行数据,每行数据含空格
int n=4;
string s[n];
for (int i=0;i<n;i++) {
string a;
getline(cin,a);
s[i]=a;
}
cout<<"输出:\n";
for (int i=0;i<n;i++)
cout<<s[i]<<endl;*/
/*//字符串分割
//hello world some any English Chinese America
int i=0;
string s[100];
string a;
while(cin>>a) { //有输入就是真
s[i++]=a;
//if (getchar()=='\n') break; //不写这句,手工按ctrl+z退出输入
} //考试时,是读取文件,正常可读
for (int j=0;j<i;j++)
cout<<s[j]<<" ";*/
/*//字符串分割到数组中:空格隔开,总长度不定,从文件中读取
//hello world some any English Chinese America
freopen("a.in","r",stdin); //r:read, standard input
freopen("a.out","w",stdout); //w:write,standard output
int i=0;
string s[100];
string a;
while(cin>>a) { //有输入就是真
s[i++]=a;
}
for (int j=0;j<i;j++)
cout<<s[j]<<" ";
fclose(stdin); //关闭标准输入stdin
fclose(stdout); //关闭标准输出stdout */
/*//分割数字字符串案例 - 用文件
freopen("a.in","r",stdin); //standard input
freopen("a.out","w",stdout); //standard output
vector<int> a;
int n;
while(cin>>n){
a.push_back(n);
}
sort(a.begin(),a.end());
for(auto x:a){
cout<<x<<" ";
}
fclose(stdin); //关闭标准输入stdin
fclose(stdout); //关闭标准输出stdout*/
//字符串分割:包装为函数
// string a[100];
// int n=-10;
// csplitstr(a,n); //引用参数
// cout<<"n="<<n<<endl;
// for (int j=0;j<n;j++)
// cout<<a[j]<<" ";
//读取一行文字,空格分开,放入vector中
//hello world some any English Chinese America
// vector<string> vs;
// string str;
// while(cin>>str) {
// vs.push_back(str);
// if (getchar()=='\n') break;
// }
// cout<<vs.size()<<endl;
// for (auto item:vs) cout<<item<<' ';
/*// 拼接用 +
string b="The great wall";
string c=" is the longest wall in the world";
string s=b+c;
cout<<s<<endl; */
/*//拼接用append,等效于 +
string b="The greal wall";
string c=" is the longest wall in the world";
b.append(c);
cout<<b<<endl; */
/*//加单个或多个重复字符
string b="Hell";
b.append(3,'A');
cout<<b<<endl; //HellAAA */
/*//加单个字符
string a="Hell";
a.push_back('o'); //等效于a.append(1,'o')
cout<<a;*/
/*//插入单个或多个字符,开头、中间都可插入
//string& insert (size_t pos, size_t n, char c)
//pos 位置
//n 个数
//c 字符
string a="ORI";
a.insert(1,2,'A'); //位置,个数,字符
cout<<a; */
/*//插入字符串,在pos的前面
//string& insert (size_t pos, const char* s);
//pos 位置
//s 插入的字符串
string b="theWall";
b.insert(3,"Great"); //位置,字符串
cout<<b; //theGreatWall */
/*//求字符串长度: length
string a="hello world";
cout<<a.size()<<endl;
cout<<a.length(); // size和length,功能一样 */
/*//遍历字符
string a="Hello World";
for (int i=0;i<a.length();i++) {
char x;
x=a[i]; //数组用法,一致
cout<<x<<' ';
} */
/*//查找,find返回下标
string a="Hello World Wonderful";
string s="W";
int found = a.find(s); //默认从头找,int=size_t
if (found==string::npos) //npos:no position
cout<<s+" canot be found!" << '\n';
else
cout<<s+" found at: " << found << '\n';
//继续找下个W,加第2个参数,表示从这个位置找
found = a.find(s,found+s.length());
if (found!=string::npos)
cout<<" found 2 times at: " << found << '\n';
else
cout<<" not found 2 times" << '\n';*/
/*// isdigit: 判断数字字符,等效于:x>='0' && x<='9'
// isupper: 判断大写,等效于:x>='A' && x<='Z'
// islower: 判断小写,等效于:x>='a' && x<='z'
string a="Hello World5";
for (int i=0;i<a.length();i++) {
char x;
x=a[i];
if (isdigit(x))
cout<<x<<" is a number"<<endl;
else if (isupper(x))
cout<<x<<" is upper"<<endl;
else if (islower(x))
cout<<x<<" is lower"<<endl;
} */
/*// 单个字符替换,把找到的W替换为X
// string& replace (size_t pos, size_t len, const string& str);
// pos 位置
// len 替换几个
// str 用啥替换
string a="Hello World";
cout<<a<<endl;
size_t found = a.find("W"); //size_t 是正整数,高级专业写法
if (found!=string::npos) { // no position,相当于找到
cout<<"'W' found at: " << found << '\n';
a.replace(found,2,"X"); //1 替换1个字符,X 替换字符
//n, 替换n个字符
cout<<a<<endl;
}
else
cout<<"'W' was not found"<<endl; */
/*//把W替换为多个字符,W -> Apple
string a="Hello World";
cout<<a<<endl;
size_t found=a.find("W");
const string svalue="Apple"; //const 是 constant的缩写
if (found!=string::npos) { // no position,相当于找到了
cout<<"'W' found at: " << found << '\n';
a.replace(found,3,"Apple"); // Hello World->Hello Appleld
// 3,从W开始算,共3位,把Wor
cout<<a<<endl;
}
else
cout<<"'W' was not found"<<endl;*/
/*// substr 截取字符
// 3 起始位置
// 5 截取的子串长度
// Hello World
// 012345678910
string a="Hello World";
string str2 = a.substr(3,5);
cout<<str2; //lo Wo */
/*// 截取pos后所有的串,用的少
string a="Hello World";
string str3 = a.substr(3,string::npos);
cout<<str3; */
/*string a="Hello World"; //推荐用
string str2 = a.substr(3); //第3个位置后所有的值
cout<<str2; //lo World */
/*// 删除 erase
// Hello World
// 012345678910
//1 位置
//3 删除字符的长度
string a="Hello World";
a.erase(1,3); // 从第1个删除3个字符
cout<<a<<endl; // 删除ell,剩余Ho World */
//遍历字符有三种方法 配置 -std=c++14
/*//方法一:访问单个字符
string a="Hello World";
for (int i=0;i<a.length();i++)
//cout<<a[i]<<" ";
cout<<a.at(i)<<' '; */
/*//方法二:迭代器访问,类似指针
string a="Hello World";
for (string::iterator it=a.begin(); it!=a.end(); it++)
cout<<*it; // 规定*,指向的元素*/
/*string a="Hello World";
for (auto it=a.begin(); it!=a.end(); it++) //迭代器简略写法
cout<<*it; */
/*//方法三:for集合法,C++高级语法,配置-std=c++11
string a="Hello World";
for (auto x:a)
cout<<x;*/
// 倒序:方法一
/*string a="abcde"; //length size一样
for (int i=a.size()-1;i>=0;i--) {
char x;
x=a[i];
cout<<x;
}*/
/*// 倒序:方法二,用倒序迭代器,rbegin = reverse + begin
string a="abcde"; // edcba
for (auto it=a.rbegin(); it!=a.rend(); ++it)
cout << *it; */
/*//倒序:方法三,用对称交换法
string a="abcde";
int n=a.length();
for (int i=0;i<n/2;i++)
swap(a[i],a[n-1-i]); //i 对称 n-1-i
for (int i=0;i<n;i++)
cout<<a[i]; */
/*//清空字符串,长度为0
string a="Hello World";
a.clear();
cout<<a<<" a.length="<<a.length(); */
/*//访问首个字符,有三种方法
string a="abcde";
cout<<a.front()<<endl; //H 第一个元素
cout<<a[0]<<endl; //第0个元素
cout<<a.at(0); //这两者等效*/
/*//访问最后一个字符,有4种方法
string a="Hello World";
cout<<a.back()<<endl; //最后一个元素
cout<<a.at(10)<<"\n"; //两者等效
cout<<a[10]<<endl;
cout<<a.at(a.length()-1)<<endl; //因为从0开始
cout<<a.length()<<endl;*/
/*//比较字符串大小 方法一
string str1 ("green apple");
string str2 ("red apple");
int ret=str1.compare(str2);
if (ret!=0)
cout << str1 << " is not " << str2 << '\n';
else if (ret==0) {
cout<<"same"<<endl;
}
if (ret>0) {
cout<<"str1 is bigger than str2"; // 因为g在r的前面,所以小
}
if (ret<0) {
cout<<"str1 is smaller than str2"; // 因为g在r的前面,所以小
} */
/*//比较字符串大小 方法二
string str1 ("green apple");
string str2 ("red apple");
if (str1>str2)
cout<<"str1 is bigger than str2";
else if (str1==str2)
cout<<"str1 equals str2";
else if (str1<str2)
cout<<"str1 is smaller than str2";*/
//排序:对所有字母排序
/*string a="orange";
sort(a.begin(),a.end()); //aegnor,默认升序
cout<<a;*/
/*string a="orange";
sort(a.begin(),a.end(),greater<char>()); //aegnor,降序
cout<<a;*/
/*string a="orange";
sort(a.begin(),a.end(),cmp); //自定义排序
cout<<a; */
//排序:对部分字母排序
/*string a="orange";
sort(a.begin()+1,a.begin()+4); //部分排序,rang这4个字符排
//结果是oanrge
//左闭右开区间,前面算,后面不算
cout<<a;*/
//字符串转数字
/*string a="0001";
int x=stoi(a);
cout<<x;
//cout<<++x;*/
//数字转字符串
/*int x=1234;
string a=to_string(x);
cout<<a;*/
/*//字符串转小数
string a="1234.56";
double x=stod(a);
cout<<x; */
/*//小数转字符串
double x=1234.56;
string a=to_string(x);
cout<<a; //1234.560000,默认6位小数,0作为字符也转换 */
// 以下是较高要求,选讲
// 字符串:变大写
// string str ="aaaBBBcde";
// //printf("str:%s \n", str.c_str());
// cout<<str<<endl;
// transform(str.begin(), str.end(), str.begin(), ::toupper);
// //printf("str:%s \n", str.c_str());
// cout<<str<<endl;
//::toupper 的意思是 "从全局作用域中引用名为 toupper 的函数"
// 字符串:变小写
// string str ="aaaBBBcde";
// //printf("str:%s \n", str.c_str());
// cout<<str<<endl;
// transform(str.begin(), str.end(), str.begin(), ::tolower);
// //printf("str:%s \n", str.c_str());
// cout<<str<<endl;
//分割数字字符串到数组中
// vector<int> v;
// string s="12 65 73 86 97"; //有多个元素
// //string s="12"; //有1个元素
// v=csplit(s);
// for (auto x:v) cout<<x<<' ';
// string src;
// string s1="",s2="";
// for (int i=0;i<2;i++) {
// getline(cin,src);
// string s=removeSpace(src);
// transform(s.begin(), s.end(), s.begin(), ::tolower); //变小写
// if (s1=="") s1=s;
// if (s1!="") s2=s;
// }
// if (s1==s2) cout<<"YES";
// else cout<<"NO";
//逗号分割,试试
// string s="I,am,a,student";
// vector<string> v;
// v=csplitStr(s,",");
// for (auto item:v) cout<<item<<endl;
// string src="8 9 4 3 +*-";
// string res=removeSpace(src);
// cout<<res;
return 0;
}
// string s="@^@";
// s=rjust(s,9);
// cout<<s;
/*
左边填充字符串,右边保留原始串,right just have,仿python函数名
参数:
str: 原始字符串,不可改
s: 最后字符串的长度
paddedChar:要填充的字符,默认是空格
返回值:
左边填充好的字符串
*/
//string rjust(string const &str, size_t s, char paddedChar = ' ') {
// if (str.size()<s)
// return string(s-str.size(),paddedChar)+str; //第6个构造函数
// else
// return str;
//}