How to find the the last occurrence of a substring in a string with C++

2 Answers

0 votes
#include <iostream>
  
int main() {
    std::string s = "c++ c php java golang nodejs";
 
    std::size_t pos = s.find_last_of("j");
    
    if (pos != std::string::npos)
        std::cout << pos << " " << s[pos];
    else
        std::cout << "not found";
}
  
  
  
/*
run:
  
26 j
  
*/

 



answered Feb 20, 2020 by avibootz
edited Feb 20, 2020 by avibootz
0 votes
#include <iostream>
  
int main() {
    std::string s = "c++ c php nodejs java golang nodejs";
  
    std::size_t pos = s.rfind("node");
    
    if (pos != std::string::npos)
        std::cout << pos << " " << s[pos];
    else
        std::cout << "not found";
}
  
  
  
/*
run:
  
29 n
  
*/

 



answered Feb 20, 2020 by avibootz
edited Feb 20, 2020 by avibootz
...