21xrx.com
2024-09-19 09:57:57 Thursday
登录
文章检索 我的文章 写文章
C++字符串分割技巧
2023-06-26 18:47:02 深夜i     --     --
C++ 字符串 分割 技巧

C++作为一门高级编程语言,在处理字符串的操作上拥有着强大的能力。字符串分割是C++编程中常见的操作之一,它可以将一个字符串按照特定的分隔符分割成多个子串,方便进行处理和使用。本文将介绍几种常用的C++字符串分割技巧。

一、使用stringstream

stringstream是用于在内存中读写字符串的类,使用它可以方便地将字符串按照特定的分隔符分割成子串。具体操作如下:


#include <iostream>

#include <sstream>

#include <string>

#include <vector>

using namespace std;

int main()

{

  string s = "apple,banana,orange,pear";

  vector<string> v; // 存储子串的vector

  stringstream ss(s); // 初始化stringstream对象

  string substr; // 存储子串的字符串

  while (getline(ss, substr, ',')) // 以逗号为分隔符读取ss对象中的字符串

  {

    v.push_back(substr); // 存储子串

  }

  // 输出结果

  for (auto i : v)

  

    cout << i << endl;

  

  return 0;

}

二、使用string::find和string::substr

string::find返回指定字符串第一次出现的位置,string::substr返回由指定位置开始的指定长度的子字符串。结合使用这两个函数可以实现字符串分割操作。具体操作如下:


#include <iostream>

#include <string>

#include <vector>

using namespace std;

int main()

{

  string s = "apple,banana,orange,pear";

  vector<string> v; // 存储子串的vector

  size_t pos = 0;

  string substr;

  while ((pos = s.find(',')) != string::npos) // 在字符串中查找逗号

  {

    substr = s.substr(0, pos); // 截取子串

    v.push_back(substr); // 存储子串

    s.erase(0, pos + 1); // 删除已获取的子串和逗号

  }

  v.push_back(s); // 存储最后一个子串

  // 输出结果

  for (auto i : v)

  

    cout << i << endl;

  

  return 0;

}

三、使用boost::split

boost::split是Boost库中提供的字符串分割函数,使用它可以方便地将字符串按照特定的分隔符分割成多个子串。代码如下:


#include <iostream>

#include <string>

#include <vector>

#include <boost/algorithm/string.hpp>

using namespace std;

using namespace boost;

int main()

{

  string s = "apple,banana,orange,pear";

  vector<string> v; // 存储子串的vector

  split(v, s, is_any_of(",")); // 分割字符串

  // 输出结果

  for (auto i : v)

  

    cout << i << endl;

  

  return 0;

}

总结:

以上是C++中三种常用的字符串分割技巧。在实际编程中,选择哪种方法取决于具体情况和个人习惯。无论使用哪种方法,都要注意边界条件、错误处理和内存安全等问题,以保证程序的稳定性和安全性。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复