Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last element in tokenized string in C++ separated by "::"?

Tags:

c++

I'm working on C++,

i have one string as follows:

string str = "rake::may.chipola::ninbn::myFuntion";

How to get last element from above string which is always after the last occurrence of "::"?

like image 212
BSalunke Avatar asked Sep 04 '12 10:09

BSalunke


People also ask

How do I get the last element of a string in CPP?

You can use string. back() to get a reference to the last character in the string. The last character of the string is the first character in the reversed string, so string. rbegin() will give you an iterator to the last character.

How to tokenize input in c++?

The common solution to tokenize a string in C++ is using std::istringstream , which is a stream class to operate on strings. The following code extract tokens from the stream using the extraction operator and insert them into a container.

How do you get a second token in Strtok?

token = strtok(Input, "-"); strcpy(first, token); token = strtok(NULL, "-"); token = strtok(Input, "."); strcpy(name, token); token = strtok(NULL, ".");


1 Answers

Use std::string::rfind() to locate the last occurrence of :: and use std::string::substr() to extract the token:

// Example without confirming that a '::' exists.
std::string last_element(str.substr(str.rfind("::") + 2));
like image 59
hmjd Avatar answered Oct 01 '22 16:10

hmjd