一、字符串读取
1. cin每次只能读入单个单词,该单词中间不能有空格,遇到空格则停止读取。
#include <iostream>
using namspace std;
cin>>a;//把键盘的数据放到变量a里。
cout<<"hello\n";//字符串数据流动到屏幕。
2. getline可以读入一条语句,可以包含空格,遇到回车终止。
- 函数调用getline();从标准输入流对象cin(即键盘)连续读取字符(包括空格符),直到遇到换行符为止。
- 读取的这些字符放入string类型的变量s中并丢弃换行符。
- 其中,在键入程序输入过程中按下回车时,会在输入流中插入一个换行符。
#include<iostream> //getline()同样属于命名空间std。
#include <string> //注意!使用getline要包含头文件string。
using namespace std;
string s;
getline(s,cin);
3. C++中本质上有两种getline函数:
- 一种在头文件<istream>中,是istream类的成员函数。
- 在<istream>中的getline函数有两种重载形式。
- <istream>中的getline函数的作用是从istream中读取至多n个字符保存在s对应的数组中。即使还没读够n个字符,如果遇到换行符'\n'(第一种形式)或delim(第二种形式),则读取终止,'\n'或delim都不会被保存进s对应的数组中。
istream& getline (char* s, streamsize n );
istream& getline (char* s, streamsize n, char delim );
- 一种在头文件<string>中,是普通函数。
- 在<string>中的getline函数有四种重载形式.
- 用法和上一种类似,不过要读取的istream是作为参数is传进函数的。读取的字符串保存在string类型的str中。
istream& getline (istream& is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream& is, string& str);
istream& getline (istream&& is, string& str);
二、字符串切片
按空格切分字符串的方法实现:split()
#include<iostream>
#include <sstream>
#include <string>
#include<vector>
using namespace std;
void split1(string str,vector<string> &ves);//声明
int main()
{
string str="the quick red fox jumps over the slow red turtle";
vector<string> ves;
split1(str, ves); //字符串切片后存到ves里面
for(auto v:ves) //输出单个字符串
cout<<v<<endl;
return 0;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
void split1(string str,vector<string> &ves)
{
istringstream ss(str);
string s;
while(ss >> s)
{
ves.push_back(s);
}
}
1. 指定字符分割
//指定字符分割
string s="123@456";
string[] a=s.split("@");
cout<<a[0]<<endl; //123
cout<<a[1]<<endl; //456
2. 使用正则表达式作为分隔符(separator)
- 用|竖线去分割某字符,因为|本身是正则表达式中的一部分,所以需要\去转义,而\正好也是正则表达式中的字符,所以还需要一个\,既需要使用两个\才可以。
- 对于某些特殊字符,如果字符串正好是正则的一部分,那么就需要转义才能使用。
- 这些字符包括 |,+,,^,$, / , |, [, ], (, ), -, ., * 等,因为他们是正则表达式中的一部分,所以如果想要用该字符本身,这些字符需要进行转移才能表示它本身。
string s="123|abc";
string []b=s.split("\\|");
cout<<b[0]<<endl; //123
cout<<b[1]<<endl; //abc
3. 使用空格作为separator
string s="hello world";
string []b=s.split(" ");
cout<<b[0]<<endl; //hello
cout<<b[1]<<endl; //world