Alon Shmiel
Alon Shmiel

Reputation: 7121

insert sub string to another string

I have the next strings:

string str1 = "1,123456,name1,4";
string str2;

I want to insert to str2, the string of str1 (from the 9th letter till the ,).

so str2 should be: name1

if str1 = "2,234567,namenamename,5", so str2 will be: namenamename (again: from the 9th letter till the ,).

I don't want to use strtok.

any help appreciated!

Upvotes: 3

Views: 71

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126442

You could use std::string::find() in combination with std::string::substr():

std::string::size_type pos = 9;
std::string str1 = "1,123456,name1,4";
std::string::size_type commaPos = str1.find(',', pos);
if (commaPos == std::string::npos)
{
    commaPos = str1.length();
}

std::string str2 = str1.substr(pos, commaPos - pos);

Here is a live example.

Upvotes: 4

Related Questions