How to get the last N characters of a string in C++

1 Answer

0 votes
#include <iostream>

std::string get_last_n_characters(std::string const& s, size_t const length) {
  if (length >= s.size()) { 
      return s; 
  }
  return s.substr(s.size() - length);
} 

int main() {
    std::string s = "c++ c php java golang nodejs";
    const int N = 6;
    
    std::string last_n_ch = get_last_n_characters(s, N);
    
    std::cout << last_n_ch;
}



/*
run:

nodejs

*/

 



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

Related questions

1 answer 105 views
2 answers 278 views
1 answer 99 views
1 answer 118 views
2 answers 189 views
2 answers 165 views
...