C++ 字符串分割
背景
在开发过程中,会遇到字符串分割的需求。
解决方法
使用C++ 提供的方法
方法1:size_t find_first_of (char c, size_t pos = 0) const; // 从pos位置开始,查找字符c,并返回字符c的首次出现的位置。
方法2:string substr (size_t pos = 0, size_t len = npos) const; //截取从pos位置开始(包括pos位置)长度为npos的字符串。
测试代码:
以下为测试代码。该代码主要用于截取str字符串变量中的用户名和密码,其中用户名位user,密码为bestwishes。
#include <string>
#include <iostream>
using namespace std;
int main(){
string str("/r/nusername=user&password=bestwishes HTTP/1.1\r\nHost");
size_t end = str.find_first_of(" ");//使用空格符分割字符串
//异常处理
if(end==std::string::npos){
return 0;
}
string namepasswd = str.substr(0,end);
size_t spUserPasswd = namepasswd.find_first_of("&");
//异常处理
if(spUserPasswd==std::string::npos){
return 0;
}
string userNameOri = namepasswd.substr(0,spUserPasswd);
string passwdOri = namepasswd.substr(spUserPasswd,end);
size_t spuserName = userNameOri.find_first_of("=");
size_t sppasswd = passwdOri.find_first_of("=");
//异常处理
if(spuserName==std::string::npos){
return 0;
}
//异常处理
if(sppasswd==std::string::npos){
return 0;
}
cout<<userNameOri<<endl;
cout<<passwdOri<<endl;
cout<<spuserName<<endl;
cout<<sppasswd<<endl;
string userName = userNameOri.substr(spuserName+1,userNameOri.length());
string passwd = passwdOri.substr(sppasswd+1,passwdOri.length());
cout<<userName<<endl;
cout<<passwd<<endl;
}
参考文档:
http://www.cplusplus.com/reference/string/string/find_first_of/
http://www.cplusplus.com/reference/string/string/substr/