user3290180
user3290180

Reputation: 4410

C++ string split and manipulation

The strings are all this way:

 string s="name_number";

I'd like to separate the name from the number and get two string "name" and "number". Then I need the number to do an addition:

int new_number=number+10;

and rebuild the string with "name_newnumber". is there a smart and fast way to do that? It's program with real time constraints so it should be as fast as possible. I only came up with split or find_first_of but I was wondering if there is something better

Upvotes: 1

Views: 1938

Answers (3)

Joseph Mansfield
Joseph Mansfield

Reputation: 110768

You can easily extract everything with a std::istringstream:

std::istringstream iss(s);

std::string name;
std::getline(iss, name, '_');
int number;
iss >> number;

Then do whatever you want with number to get newnumber, and then concatenate it all together again:

std::string newstring = name + "_" + std::to_string(newnumber);

This could easily do with some more error checking though (for example, if the stream extraction fails).

Upvotes: 4

Vlad from Moscow
Vlad from Moscow

Reputation: 311126

Try the following as an idea.

#include <iostream>
#include <string>

int main() 
{
    std::string s = "name_5";

    std::cout << s << std::endl;

    std::string::size_type n = s.rfind( '_' );

    if ( n != std::string::npos )
    {
        s.replace( n + 1, std::string::npos, 
                   std::to_string( std::stoi( s.substr( n + 1 ) ) + 10 ) );
    }

    std::cout << s << std::endl;

    return 0;
}

The output is

name_5
name_15

Take into account that I used method rfind instead of find. In this case the name may contain an embedded underscore.

For example if you will initialize the string as

std::string s="Main_Name_  5";

you will get

Main_Name_  5
Main_Name_15

Upvotes: 3

Niall
Niall

Reputation: 30624

Something like this should do the trick

 std::string abc = "name_10";
 std::string name = abc.substr(0, abc.find('_'));
 int i = std::stoi(abc.substr(abc.find('_') + 1));
 // change i
 ++i;
 abc = name + '_' + std::to_string(i);

Upvotes: 2

Related Questions