Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ How to split string into two strings based on the last '.'

Tags:

c++

split

trim

I want to split the string into two separate strings based on the last '.' For example, abc.text.sample.last should become abc.text.sample.

I tried using boost::split but it gives output as follows:

abc
text
sample
last

Construction of string adding '.' again will not be good idea as sequence matters. What will be the efficient way to do this?

like image 991
Namitha Avatar asked Mar 04 '16 10:03

Namitha


People also ask

How to achieve the splitting of strings in C++?

Different method to achieve the splitting of strings in C++ 1 Use strtok () function to split strings 2 Use custom split () function to split strings 3 Use std::getline () function to split string 4 Use find () and substr () function to split string

How do you split a string into two parts?

To split a string we need delimiters - delimiters are characters which will be used to split the string. Suppose, we've the following string and we want to extract the individual words. char str[] = "strtok needs to be called several times to split a string"; The words are separated by space.

How does the split () function work in Python?

The first thing the split () function does is to obtain the length of the original string: If the split ( offset) is greater than the string’s length, the function returns 0, failure. (The function can “split” a string the same length as the original string, in which case you end up with a copy of the original string and an empty string.)

What is the use of split in Java?

In Java, split () is a method in String class. // expregexp is the delimiting regular expression; // limit is the number of returned strings public String [] split (String regexp, int limit); // We can call split () without limit also public String [] split (String regexp)


Video Answer


3 Answers

Something as simple as rfind + substr

size_t pos = str.rfind("."); // or better str.rfind('.') as suggested by @DieterLücking
new_str = str.substr(0, pos);
like image 57
Serge Ballesta Avatar answered Oct 04 '22 01:10

Serge Ballesta


std::string::find_last_of will give you the position of the last dot character in your string, which you can then use to split the string accordingly.

like image 26
stellarossa Avatar answered Oct 04 '22 00:10

stellarossa


Make use of function std::find_last_of and then string::substr to achieve desired result.

like image 41
Digital_Reality Avatar answered Oct 04 '22 01:10

Digital_Reality