使用字符串分隔符(标准 C++)解析(拆分)C++ 中的字符串 [英] Parse (split) a string in C++ using string delimiter (standard C++)

查看:45
本文介绍了使用字符串分隔符(标准 C++)解析(拆分)C++ 中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码解析 C++ 中的字符串:

I am parsing a string in C++ using the following:

using namespace std;

string parsed,input="text to be parsed";
stringstream input_stringstream(input);

if (getline(input_stringstream,parsed,' '))
{
     // do some processing.
}

使用单个字符分隔符进行解析很好.但是如果我想使用字符串作为分隔符怎么办.

Parsing with a single char delimiter is fine. But what if I want to use a string as delimiter.

示例:我想拆分:

scott>=tiger

>= 作为分隔符,这样我就可以得到 scott 和 Tiger.

with >= as delimiter so that I can get scott and tiger.

推荐答案

您可以使用std::string::find() 函数来查找字符串分隔符的位置,然后使用 std::string::substr() 获取令牌.

You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token.

示例:

std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"

  • find(const string& str, size_t pos = 0) 函数返回str 在字符串中第一次出现的位置,或npos 如果未找到字符串.

    • The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found.

      substr(size_t pos = 0, size_t n = npos) 函数返回对象的子字符串,从位置 pos 开始,长度为 npos.

      The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos.

      如果有多个定界符,提取一个token后,可以去掉(含定界符)进行后续提取(如果想保留原字符串,只需使用s = s.substr(pos + delimiter.length());):

      If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length());):

      s.erase(0, s.find(delimiter) + delimiter.length());
      

      通过这种方式,您可以轻松地循环获取每个令牌.

      This way you can easily loop to get each token.

      std::string s = "scott>=tiger>=mushroom";
      std::string delimiter = ">=";
      
      size_t pos = 0;
      std::string token;
      while ((pos = s.find(delimiter)) != std::string::npos) {
          token = s.substr(0, pos);
          std::cout << token << std::endl;
          s.erase(0, pos + delimiter.length());
      }
      std::cout << s << std::endl;
      

      输出:

      scott
      tiger
      mushroom
      

      这篇关于使用字符串分隔符(标准 C++)解析(拆分)C++ 中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆