在 C++ 中是否有内置的拆分字符串的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/599989/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:11:20  来源:igfitidea点击:

Is There A Built-In Way to Split Strings In C++?

c++stringsplit

提问by jimi hendrix

well is there? by string i mean std::string

有吗?字符串我的意思是 std::string

回答by heeen

Here's a perl-style split function I use:

这是我使用的 perl 风格的拆分函数:

void split(const string& str, const string& delimiters , vector<string>& tokens)
{
    // Skip delimiters at beginning.
    string::size_type lastPos = str.find_first_not_of(delimiters, 0);
    // Find first "non-delimiter".
    string::size_type pos     = str.find_first_of(delimiters, lastPos);

    while (string::npos != pos || string::npos != lastPos)
    {
        // Found a token, add it to the vector.
        tokens.push_back(str.substr(lastPos, pos - lastPos));
        // Skip delimiters.  Note the "not_of"
        lastPos = str.find_first_not_of(delimiters, pos);
        // Find next "non-delimiter"
        pos = str.find_first_of(delimiters, lastPos);
    }
}

回答by Martin Cote

There's no built-in way to split a string in C++, but boostprovides the string algolibrary to do all sort of string manipulation, including string splitting.

在 C++ 中没有分割字符串的内置方法,但是boost提供了字符串算法库来执行所有类型的字符串操作,包括字符串分割

回答by MSalters

Yup, stringstream.

是的,串流。

std::istringstream oss(std::string("This is a test string"));
std::string word;
while(oss >> word) {
    std::cout << "[" << word << "] ";
}

回答by strager

STL strings

STL 字符串

You can use string iterators to do your dirty work.

您可以使用字符串迭代器来完成您的脏活。

std::string str = "hello world";

std::string::const_iterator pos = std::find(string.begin(), string.end(), ' '); // Split at ' '.

std::string left(str.begin(), pos);
std::string right(pos + 1, str.end());

// Echoes "hello|world".
std::cout << left << "|" << right << std::endl;

回答by Igor Oks

void split(string StringToSplit, string Separators)
{
    size_t EndPart1 = StringToSplit.find_first_of(Separators)
    string Part1 = StringToSplit.substr(0, EndPart1);
    string Part2 = StringToSplit.substr(EndPart1 + 1);
}

回答by dirkgently

The answer is no. You have to break them up using one of the library functions.

答案是不。您必须使用库函数之一将它们分解。

Something I use:

我使用的东西:

std::vector<std::string> parse(std::string l, char delim) 
{
    std::replace(l.begin(), l.end(), delim, ' ');
    std::istringstream stm(l);
    std::vector<std::string> tokens;
    for (;;) {
        std::string word;
        if (!(stm >> word)) break;
        tokens.push_back(word);
    }
    return tokens;
}

You can also take a look at the basic_streambuf<T>::underflow()method and write a filter.

你也可以看看basic_streambuf<T>::underflow()方法,写一个过滤器。

回答by Mr.Ree

What the heck... Here's my version...

什么鬼……这是我的版本……

Note: Splitting on ("XZaaaXZ", "XZ") will give you 3 strings. 2 of those strings will be empty, and won'tbe added to theStringVector if theIncludeEmptyStrings is false.

注意:拆分 ("XZaaaXZ", "XZ") 将为您提供 3 个字符串。其中 2 个字符串将为空,如果 theIncludeEmptyStrings 为 false ,则不会添加到 StringVector。

Delimiter is notany element in the set, but rather matches that exact string.

分隔符不是集合中的任何元素,而是匹配该确切字符串。

 inline void
StringSplit( vector<string> * theStringVector,  /* Altered/returned value */
             const  string  & theString,
             const  string  & theDelimiter,
             bool             theIncludeEmptyStrings = false )
{
  UASSERT( theStringVector, !=, (vector<string> *) NULL );
  UASSERT( theDelimiter.size(), >, 0 );

  size_t  start = 0, end = 0, length = 0;

  while ( end != string::npos )
  {
    end = theString.find( theDelimiter, start );

      // If at end, use length=maxLength.  Else use length=end-start.
    length = (end == string::npos) ? string::npos : end - start;

    if (    theIncludeEmptyStrings
         || (   ( length > 0 ) /* At end, end == length == string::npos */
             && ( start  < theString.size() ) ) )
      theStringVector -> push_back( theString.substr( start, length ) );

      // If at end, use start=maxSize.  Else use start=end+delimiter.
    start = (   ( end > (string::npos - theDelimiter.size()) )
              ?  string::npos  :  end + theDelimiter.size()     );
  }
}


inline vector<string>
StringSplit( const  string  & theString,
             const  string  & theDelimiter,
             bool             theIncludeEmptyStrings = false )
{
  vector<string> v;
  StringSplit( & v, theString, theDelimiter, theIncludeEmptyStrings );
  return v;
}

回答by Marco Kinski

There is no common way doing this.

没有通用的方法可以做到这一点。

I prefer the boost::tokenizer, its header only and easy to use.

我更喜欢boost::tokenizer,它只有标题并且易于使用。

回答by Allen Ratcliff

A fairly simple method would be to use the c_str() method of std::string to get a C-style character array, then use strtok() to tokenize the string. Not quite as eloquent as some of the other solutions listed here, but it's easy and works.

一个相当简单的方法是使用 std::string 的 c_str() 方法来获取 C 风格的字符数组,然后使用 strtok() 来标记字符串。不像这里列出的其他一些解决方案那样雄辩,但它很容易并且有效。

回答by strager

C strings

C字符串

Simply insert a \0where you wish to split. This is about as built-in as you can get with standard C functions.

只需\0在要拆分的位置插入一个。这与使用标准 C 函数可以获得的内置功能差不多。

This function splits on the first occurance of a charseparator, returning the second string.

此函数在char分隔符第一次出现时拆分,返回第二个字符串。

char *split_string(char *str, char separator) {
    char *second = strchr(str, separator);
    if(second == NULL)
        return NULL;

    *second = '##代码##';
    ++second;
    return second;
}