C++ 字符串分割

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/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值