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

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

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

相关标签:
10条回答
  • 2020-12-08 11:32

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

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

    Yup, stringstream.

    std::istringstream oss(std::string("This is a test string"));
    std::string word;
    while(oss >> word) {
        std::cout << "[" << word << "] ";
    }
    
    0 讨论(0)
  • 2020-12-08 11:34

    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.

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

    STL strings

    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;
    
    0 讨论(0)
  • 2020-12-08 11:40

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

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-08 11:40

    C strings

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

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

    char *split_string(char *str, char separator) {
        char *second = strchr(str, separator);
        if(second == NULL)
            return NULL;
    
        *second = '\0';
        ++second;
        return second;
    }
    
    0 讨论(0)
提交回复
热议问题