1

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 ;(

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
LuffyPapa
  • 21
  • 2
  • You can search the string backwards for your delimiter character using `rbegin` and `rend` in combination with `std::find()`. – πάντα ῥεῖ Oct 28 '22 at 14:32
  • Read about [`std::basic_string::rfind`](https://en.cppreference.com/w/cpp/string/basic_string/rfind). In particular, the variation marked "(4)". – Pete Becker Oct 28 '22 at 16:45
  • Reopened. The question is about searching for a **single character** delimiter. The claimed duplicate is about searching for a **string** delimiter. – Pete Becker Oct 28 '22 at 16:49

2 Answers2

0

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 "/,".

Try it online!

#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
Arty
  • 14,883
  • 6
  • 36
  • 69
0

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
Jason
  • 36,170
  • 5
  • 26
  • 60