C++ 字符串分割
来源:互联网 发布:算法分析与设计 王晓东 编辑:程序博客网 时间:2024/06/03 19:52
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 0
- 字符串分割(C/C++)
- C字符串分割
- C字符串分割
- C++MFC分割字符串
- 分割字符串(C版本)
- 字符串分割(C++)
- 字符串分割(C++)
- 字符串分割(C++)
- 字符串分割(C++)
- 字符串分割(C++)
- C字符串分割
- 字符串分割(C++)
- 字符串分割(C++)
- 常用字符串分割(C++)
- C语言字符串分割
- 字符串分割(C++)
- 字符串分割(C++)
- 字符串分割(C++)
- Spring Boot 学习22--导入XML配置
- Activity C中关闭Activity A的方法
- 第一篇博客
- MySQL
- 转 A 、B两张表,找出ID字段中,存在A表,但是不存在B表的数据
- C++ 字符串分割
- 常见小效果之懒加载
- 图片上传的设置
- Hibernate:命名SQL查询
- iOS WebView与Native交互
- Rocketmq整体分析
- PhotoShop 快捷键看我就够了
- 自定义ImageView
- 揭秘--组件的概念及应用