1. 基础语法格式
1.1 定义一个数组
Int a[N];
当出现,const int N 1e+9 时,上述语句才是正确的。
在main函数之外(即,全局变量)时初始化为0.
Ll a[N];
当出现,typedef long long ll;时才是正确的。
1.2 输入输出
- scanf(“%[^\n]”,s); 表示只要不是回车就读进去。
- cout怎么保留小数:cout<<fixed<<setprecision(3)<<a.保留三位小数
- cin输入字符串遇到字符串结束。
- cin需要输入一整行的时候就采用:
int main()
{
string s;
getline(cin,s);
cout<<s;
return 0;
}
- 对cin进行加速操作来避免超时:
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
//取消同步流
1.3 String
- 字符串的声明和初始化:
#include<iostream>
#include<string>
int main()
{
using namespace std;
//取消同步流
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
//声明并初始化一个字符串
string str1="hello,world";
//使用已存在的字符串来初始化字符串
string str2=str1;
//使用部分字符串
string str3=str1.substr(0,5);//补充:substr(起始位置,长度)
//使用字符数组来初始化字符串
const char* charArray="hello";
string str4=charArray;
//使用重复的字符来初始化字符串
string str5(5,'A');
cout<<"str1=:"<<str1<<endl;//endl最后输出一个换行符并刷新输出缓冲区
cout<<"str2=:"<<str2<<endl;
cout<<"str3=:"<<str3<<endl;
cout<<"str4=:"<<str4<<endl;
cout<<"str5=:"<<str5<<endl;
}
验证输出结果:
- 补充:两个库函数的区别:
#include<bits/stdc+.h>是一个非标准化的头文件,它包含了所有标准C++库的头文件。因此,当使用这个头文件时,不需要单独包含其他头文件,就可以使用常用的C++库函数和对象。
而#include:是标准C++库的头文件之一,它包含了输入输出流的定义,如cout和cin。这个头文件只包含输入输出流相关的内容,如果需要使用其他函数和对象,则需要包含其他相应的头文件。
因为#include<bits/stdc+.h>不是标准化的头文件,所以在编写一些需要跨平台的代码时,最好使用标准库头文件来确保代码的可移植性。
1.4. 各种基本操作
**获取字符串**
string str1="hello,world";
int length=str1.length();
cout<<length;
**//拼接字符串(+或者是append)**
string str1="hello";
string str2="world";
string str3=str1+','+str2;
string str4=str1.append(,).append(str2);
**//字符串查找**
string str1="hello,world";
size_t pos=str.find("world");//查找子字符串的位置
//注意:这里的返回结果是子字符串的首位置
if(pos!=string::npos) //npos的意思是-1,也就是从右开始数第一个元素(简而言之就是找到头了也没有找到)
{
cout<<pos;
}
else
cout<<"Not found.";
**//提取子字符串(substr)**
string str1="hello,world";
string substr1=str1.substr(7,5); //一定要注意最后一个参数不要越界
cout<<substr1;
**字符串比较**
int result str1.compare(str2);
//结果有三种形式:1.等于0,两个字符串相等。2.<0,第一个字符串小于第二个字符串。
//大于小于的判断规则:字典序的比较方法。从小到大一个一个比较,一旦遇到不相等的字符就确定大小关系。
//实际上两个字符串也可以直接用大于小于号来比较。
1.5 常用的遍历string的方法
- for循环:
string str1="hello";
for(int i=0;i<str1.length();i++)
cout<<str1[i];
- auto枚举
string str1="hello";
for(auto &i:str1)//使用&表示引用类型
{
cout<<i;
i='a';//将i的值修改为a
}
cout<<"\n";
cout<<str1;
1.6 例题
反转字符串–蓝桥题库OJ250
- 解法一:字符串不改变,只是进行倒序输出
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
string s;
getline(cin,s);//读入一行
for(int i=(int)s.length()-1;i>=0;i--)
cout<<s[i];
return 0;
}
- 解法二:字符串实际上发生改变
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
string s;
getline(cin,s);//读入一行
reverse(s.begin(),s.end());
cout<<s<<"\n";
return 0;
}
- 折半对换
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
string s;
getline(cin,s);
int len=s.length();//读入一行
for(int i=0;i<len/2;i++)
swap(s[i],s[len-i-1]);
cout<<s<<"\n";
return 0;
}