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?
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
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.
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.)
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)
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);
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.
Make use of function std::find_last_of and then string::substr to achieve desired result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With