蓝桥杯以及面试题需要掌握的知识点(字符串(String)部分)

1,如何从字符串数组里取单个字符:

 

比如string pinyin[5]={"ling","yi","er","san","si"};

    取ling中的  ’l’  ,pinyin[1][1],这样是错误的。

可以:

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];

}

 

注:string 定义的字符串,从0下标开始.

 

 

 

 

 

2,对字符串排序(对字母)

用Sort 对字符串排序(从小到大)

//从小到大
#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;
}

从大到小

#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 s1="a";
	string s2="bc";
	string s3=s1+s2;
	cout<<s3;


//二,
	s2+="ccc";
	cout<<s2;

四,查找子串

使用find函数

#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<<"不存在";
 }

   
 //结果为不存在 
	 
}

五,字符串转数字

整数:atoi(s.c_str()), 小数 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

六,数字转字符串

to_string(i);

//注意小数转字符串会自动填充到小数点后六位,没有数字的会自动补零;

 

    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

七,字符串一维数组,可以当二维使用(这句话,不够严谨,但这样便于直接运用)

    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;
	}

结果演示

9d3331055090422d80a450a87e1b9b63.png

猜你喜欢

转载自blog.csdn.net/qq_58136559/article/details/129867929