跳到正文

算法·理论

字符串string的应用

原文
文章信息与版本

文章信息

收录
2026年8月6日
更新
2026年8月6日
篇幅
约 2 分钟

版本

  1. v1当前
C++
#include <bits/stdc++.h>
using namespace std;
int main(){
//	1.字符串的拼接 
	string s1="Hello";
	string s2="world";
	string s3=s1+s3;
	cour<<s3<<endl;
	s3.append("12345");
	cout<<s3<<endl;
//	2.字符串输入输出
	cin>>s3; //cin输入字符串,以空格或回车结束 
	cout<<s3<<endl; 
//	3.读入一整行字符
	getline(cin,s3);
	cout<<s3<<endl;
//	4.获取字符串的长度
	int lens1=s1.length();
	cout<<lens1<<endl;
	int lens2=s2.size();
	cout<<lens2<<endl;
//	5.当字符数组使用
	cout<<s1[0]<<endl;
	cout<<s2<<[2]<<endl;
//	6.string字符串和字符数组互换
	char a[100];
	int lens=s1.copy(a,s1.size()); 
	printf("%s\n",a);
	
	strcpy(a,s2.c_str());
	printf("%s\n",a);
//	7.字符串大小的比较
	s1="abc";
	s2="abb";
	if(s1>s2) cout<<"yes1"<<endl;
	s1="Abc";
	if(s1>s2) cout<<"yes2"<<endl; 
//	8.求字符串的子串
	s1="hello world";
	s2=s1.substr(2,5);
	cout<<s2<<endl; 
	s2=s1.substr(3);
	cout<<s2<<endl; 
//	9.查找字符串的字串 
	int n=s1.find("world");
	cout<<n<<endl;
	cout<<s1.find("o")<<endl;\
	cout<<s1.rfind("o")<<endl; 
	cout<<s1.find("abcdef")<<endl;
//	10.替换字符串
//	s1.replace(0,5,"school");
//	cout<<s1;
// 	11.删除字串
	s1.erase(3,2);
	cout<<s1<<endl;
//	12.插入字串
	s1.insert(5,"aaaaaaaa");
	cout<<s1<<endl; 
	return 0;
}
原文