簡體   English   中英

使用多個分隔符將一個字符串拆分為多個字符串而不刪除?

[英]Splitting a string into multiple strings with multiple delimiters without removing?

我使用boost框架,因此可能會有所幫助,但是我沒有找到必要的功能。

對於通常的快速拆分,我可以使用:

string str = ...;
vector<string> strs;
boost::split(strs, str, boost::is_any_of("mM"));

但會刪除m和M個字符。

我也不擅長使用regexp,因為它會在字符串中搜索符合定義模式的最長值。

PS有很多類似的問題,但是它們僅以其他編程語言描述了此實現。

未經測試,但可以使用vector<boost::iterator_range<std::string::iterator>> (而不是使用vector<string> ,因此您可以為每個標記獲得一對主字符串的迭代器。然后從(范圍-1的開始[只要范圍的begin()不是主字符串的begin() ,到范圍的結束)

編輯:這是一個示例:

#include <iostream>
#include <string>

#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/range/iterator_range.hpp>

int main(void)
{
  std::string str = "FooMBarMSFM";

  std::vector<boost::iterator_range<std::string::iterator>> tokens;

  boost::split(tokens, str, boost::is_any_of("mM"));

  for(auto r : tokens)
  {
    std::string b(r.begin(), r.end());
    std::cout << b << std::endl;
    if (r.begin() != str.begin())
    {
      std::string bm(std::prev(r.begin()), r.end());
      std::cout << "With token: [" << bm << "]" << std::endl;
    }
  }
}

您的需求超出了split的概念。 如果要保留'm或M',則可以通過strstrstrchrstrtokfind函數編寫一個特殊的拆分。 您可以更改一些代碼以產生靈活的split功能。 這是一個例子:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void split(char *src, const char *separator, char **dest, int *num)
{
    char *pNext;
    int count = 0;

    if (src == NULL || strlen(src) == 0) return;
    if (separator == NULL || strlen(separator) == 0) return; 

    pNext = strtok(src,separator);

    while(pNext != NULL)
    {
        *dest++ = pNext;
        ++count;
        pNext = strtok(NULL,separator);
    }

    *num = count;
}

此外,您可以嘗試boost::regex

我當前的解決方案如下(但它不是通用的,看起來太復雜了)。

我選擇了一個不會出現在該字符串中的字符。 在我的情況下,它是“ |”。

string str = ...;
vector<string> strs;
boost::split(strs, str, boost::is_any_of("m"));
str = boost::join(strs, "|m");
boost::split(strs, str, boost::is_any_of("M"));
str = boost::join(strs, "|M");
if (boost::iequals(str.substr(0, 1), "|") {

    str = str.substr(1);
}
boost::split(strs, str, boost::is_any_of("|"));

我加“ |” 每個符號m / M之前,除了字符串中的第一個位置。 然后我將字符串拆分為子字符串,並刪除此多余字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM