Cheap and nasty way, closest to what you already have: use std::string::c_str()
std::string const s{"abcde"};
char const *c = s.c_str();
for (std::size_t i=0; i<s.size(); ++i)
std::cout << c+i << '\n';
The more string
-like way is to use std::string::substr
:
std::string const s{"abcde"};
for (std::size_t i=0; i<s.size(); ++i)
std::cout << s.substr(i) << '\n';
Note that the second approach does involve allocating memory for the new string
every time, but I think here the benefit of clarity (using a function specifically named and designed for what you are trying to do), and avoiding raw pointers (often a cause of confusion for beginners) both outweigh the performance (non-)issue here.
A more modern approach that combines the clarity of using specific C++ components designed for what you want, with avoiding extra allocations, is to use std::experimental::string_view
, which is designed to wrap an existing string of characters:
std::string const s{"abcde"};
std::experimental::string_view sv{s};
for (std::size_t i=0; i<s.size(); ++i) {
std::cout << sv << '\n';
sv.remove_prefix(1);
}
std::experimental::string_view::remove_prefix
does what you might expect: shrinks the view of the string it is wrapping at the front, by the number specified.
string_view
is not technically part of The Standard yet, so I don't really recommend it for production use, since you won't get good cross-platform support. But it's quite fun to learn about. You might consider the very similar (not coincidentally) component, boost::string_ref
to be production quality.
Also, please reconsider your use of what are often considered bad practices: using namespace std;
and endl
(those are links to explanations).