Like we have string = "Cow eat Grass/Cat eat mouse/Dog eat meat/Fish eat worm/Snake eat mouse" I try to make function like:
std::string getTheLastAnimalText(const std::string& source)
{
// .... Can you help here :)
return "Snake eat mouse";
I try to make this function but i can't ;(
CodePudding user response:
You can use std::basic_string::find_last_of and std::basic_string::substr, like following.
Also if you need supporting several delimiters, e.g. also comma, then replace in my code "/"
with "/,"
.
#include <string>
#include <iostream>
std::string getTheLastAnimalText(std::string const & source) {
return source.substr(source.find_last_of("/") 1);
}
int main() {
std::cout << getTheLastAnimalText("Cow eat Grass/Cat eat mouse/Dog eat meat/Fish eat worm/Snake eat mouse");
}
Output:
Snake eat mouse
CodePudding user response:
You can use std::string::find_last_of
as shown below:
const std::string input = "Cow eat Grass/Cat eat mouse/Dog eat meat/Fish eat worm/Snake eat mouse";
auto const pos = input.find_last_of('/');
const auto last = input.substr(pos 1);
std::cout << last<< std::endl; //prints Snake eat mouse