1, How to get a single character from a string array:
比如string pinyin[5]={"ling","yi","er","san","si"};
Take the 'l' in ling, pinyin[1][1], this is wrong.
Can:
String word=pinyin[1];
Cout<<word[0];
#include<bits/stdc++.h>
using namespace std;
int main()
{
string pinyin[5]={"ling","yi","er","san","si"};
string word=pinyin[0];
cout<<word[0];
}
Note: The string defined by string starts from subscript 0.
2, Sort strings (letters)
Use Sort to sort strings (from small to large)
//从小到大
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s;
cin>>s;
cout<<s<<endl;
int n=s.size();
sort(s.begin(),s.end());
cout<<s;
}
from big to small
#include<bits/stdc++.h>
using namespace std;
bool px(char a,char b)
{
if(a>b)
return true;
else
return false;
}
int main()
{
string s;
cin>>s;
cout<<s<<endl;
int n=s.size();
sort(s.begin(),s.end(),px);
cout<<s;
}
3, string splicing
//一,
string s1="a";
string s2="bc";
string s3=s1+s2;
cout<<s3;
//二,
s2+="ccc";
cout<<s2;
Fourth, find the substring
use the find function
#include<bits/stdc++.h>
using namespace std;
int main()
{
string s="123441234413412351236123";
string str="0123012301230123";
string s1="123";
cout<<s.find(s1)<<endl; //返回第一个找到的子串的首位下标 结果:0
cout<<str.find(s1)<<endl;//结果:1
//如何实现查找子串的所有数量
int k=0;
int cnt=0;
while((k=s.find(s1,k))!=s.npos) //可以把npos当作结尾标志来理解
{
k++;//下一个查询的位置。
cnt++;//子串出现次数
}
cout<<cnt<<endl; //结果为五
//如何判断没有该子串
string str1="1201201201201444";
string s2 = "123";
int p=0;
p=str1.find(s2);
if(p!=str1.npos)
{
cout<<"存在";
}
else
{
cout<<"不存在";
}
//结果为不存在
}
Five, string to number
Integer: atoi(s.c_str()), decimal atof(s.c_str());
string s1 = "123";
string s2 = "123.1";
int i = atoi(s1.c_str());
double d = atof(s2.c_str());
cout<<i<<endl;//123
cout<<d<<endl;/123.1
Six, numbers to strings
to_string(i);
// Note that the conversion of decimals to strings will be automatically filled to six decimal places, and zeros will be automatically filled if there are no numbers;
float a = 12.34;
string s = to_string(a);
cout<<s<<endl; //12.340000
double c = 12.34;
string sss = to_string(c);
cout<<sss<<endl;//12.340000
double e = 12.3;
string ssss = to_string(e);
cout<<ssss<<endl;//12.300000
int b = 100;
string ss = to_string(b);
cout<<ss; //100
7. A one-dimensional array of strings can be used as a two-dimensional array (this sentence is not rigorous enough, but it is easy to use directly)
string m[10];
for(int i=0;i<10;i++)
{
cin>>m[i];
}
for(int i=0;i<10;i++)
{
for(int j=0;j<m[i].size();j++)
{
cout<<m[i][j]<<" ";
}
cout<<endl;
}
Result presentation