string的基本使用
C++基础格式
C语言语法+STL。蓝桥杯选用C++11的版本。
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main()
{
cout<<"Hello World!"<<endl;
printf("Hello World!");
return 0;
}
基本数据类型
#include <bits/stdc++.h>
using namespace std;
int main() {
int x = 3;
double d = 3.14;
char ch = 'A';
char s[] = "hello";
bool b = true;
cout << x << '\n';
cout << d << '\n';
cout << ch << '\n';
cout << s << '\n';
cout << b << '\n';
return 0;
}
string
主要用于字符串处理
string声明与初始化
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
string s1="hello world";
string s2=s1;
string s3=s1.substr(0,5);//起始位置,长度,注意不是终点位置
cout<<"s1="<<s1<<endl;
cout<<"s2="<<s2<<endl;
cout<<"s3="<<s3<<endl;
return 0;
}
利用printf输出string类型
#include <bits/stdc++.h>
using namespace std;
int main()
{
char buf[100];
scanf("%s",buf);
string str(buf);
printf("%s\n",str.c_str());//c_str()返回一个指向正规C字符串的指针, 内容与本string串相同.
//这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
return 0;
}
string基本操作
#include <bits/stdc++.h>
using namespace std;
int main()
{
//获取字符串长度(length/size)
string s1="hello world";
cout<<"s1.lenght="<<s1.length()<<endl;
cout<<"s1.size="<<s1.size()<<endl;
//拼接字符串
string s2="hello";
string s3="world";
string s4=s2+s3;
cout<<"s4="<<s4<<endl;
//字符串查找
string s5="hello world";
size_t pos1=s5.find("world");
//要用size_t类型,无符号整型,不能为负数,所以不能用int类型
size_t pos2=s5.find('d',3);//从第3个位置开始找'd'
//注意,find函数返回的是第一次出现的位置,如果没有找到,返回-1
cout<<"pos1="<<pos1<<endl;
cout<<"pps2="<<pos2<<endl;
//字符串替换
//replace(起始位置, 被替换长度, 要替换的字符串)
string s6="hello world";
s6.replace(6,5,"China");
cout<<"s6="<<s6<<endl;
//提取字符串
string s7=s6.substr(0,5);
cout<<"s7="<<s7<<endl;
//字符串比较
string s8="hello";
string s9="world";
cout<<"s8.compare(s9)="<<s8.compare(s9)<<endl;
//若hello>world,返回1
//若hello<world,返回-1
//若hello=world,返回0
return 0;
}
运行效果如下