0

Is there a reverse functionality of C++ substr which returns the substring from char 0 up till the given index? I cannot seem to find any posts here answering this question for C++. I am aware that it is possible to just reverse the string and then use substr, but I am wondering if there is a functionality which does this in one step.

6
  • 1
    You could use reverse iterators to walk a substring backwards, in-place; or copy the range (in reverse order) to another string. Commented Sep 26, 2018 at 13:45
  • Use reverse iterators and copy the number of characters you need? Commented Sep 26, 2018 at 13:45
  • 3
    Don't write "SOLVED", just click on the checkmark at the answer to accept it. Commented Sep 26, 2018 at 13:48
  • Thanks for your help, this is a rather obvious answer I wish I would have come up with myself. Commented Sep 26, 2018 at 13:49
  • @rustyx I will do so as soon as I can. Commented Sep 26, 2018 at 13:50

2 Answers 2

7

You may be looking for something like this:

std::string source = "something";
std::string dest(source.rbegin() + source.size() - given_index, source.rend());
Sign up to request clarification or add additional context in comments.

Comments

0

String doesn't have this functionality. But you can make something like this:

int count=5;
std::string str="Hello World Budulai";
std::string res(str.begin(),str.begin()+count);

This code copy to res string, from 0 to count symbol;

If you mean zero char == '\0' so you need use reverse iterators. and this will like:

std::string res(str.rbegin(),str.rbegin()+count);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.