Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ boost::split first of

Tags:

c++

split

boost

I have a function for splitting string:

boost::split(r,lines[i], boost::is_any_of("="));

Above code splits string by every "=" I want to transform this code to split by only one "=". Example:

__ga=223478=90234=234

After split:

__ga
223478=90234=234

How to do this ?

like image 768
mitch Avatar asked Feb 27 '14 15:02

mitch


People also ask

What is C in Split function?

Here 'c' is the Character because of your splitting single character (space). This C how it's work: it will convert a given string into a character.

How do you split a line by space in C++?

You can use string's find() and substr() methods to Split String by space in C++. This is more robust solution as this can be used for any delimeter.


1 Answers

Boost is not necessary for this. A possible solution would be to use std::string::find_first_of() and create two strings using std::string::substr() with the result:

#include <iostream>
#include <string>

int main()
{
    std::string name_value = "__ga=223478=90234=234";
    std::string name;
    std::string value;

    const auto equals_idx = name_value.find_first_of('=');
    if (std::string::npos != equals_idx)
    {
        name = name_value.substr(0, equals_idx);
        value = name_value.substr(equals_idx + 1);
    }
    else
    {
        name = name_value;
    }

    std::cout << name << std::endl
              << value << std::endl;

    return 0;
}

Output:

__ga
223478=90234=234
like image 179
hmjd Avatar answered Sep 30 '22 20:09

hmjd