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

前端 未结 10 2207
心在旅途
心在旅途 2020-12-08 10:56

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

相关标签:
10条回答
  • 2020-12-08 11:44
    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);
    }
    
    0 讨论(0)
  • 2020-12-08 11:54

    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't be added to theStringVector if theIncludeEmptyStrings is false.

    Delimiter is not any 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;
    }
    
    0 讨论(0)
  • 2020-12-08 11:55

    There is no common way doing this.

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

    0 讨论(0)
  • 2020-12-08 11:57

    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.

    0 讨论(0)
提交回复
热议问题