string rec_rev_str(string *str,int size){
if(size == 0){
return *str;
}
swap((*str)[0],(*str)[size]);`// size is the index from the end`
return rec_rev_str(str 1,size-1);
}
int main(){
string str = "great";
int size = 5;
int start = 0;
int end = size - 1;
string* ptr = &str;
rec_rev_str(ptr,size-1);
cout<<str<<endl;
}
- I don't understand how to point str 1 (the first index of the string like we do in an array e.g. arr 1)
CodePudding user response:
#include <iostream>
#include <string>
#include <algorithm>
// pass string by reference so we can swap in place
void reverse(std::string& input, size_t leftIndex, size_t rightIndex){
if(leftIndex < rightIndex){
// <algorithm> header has a swap implementation
std::swap(input[leftIndex], input[rightIndex]);
// increment index from left, decrement from right, and continue swapping
reverse(input, leftIndex 1, rightIndex-1);
}
}
int main() {
std::string inputString = "Hello, world!";
reverse(inputString, 0, inputString.size() - 1);
std::cout << inputString << std::endl;
return 0;
}
CodePudding user response:
string
is not an array. If you see str 1
it means that wants to read the 'next string' so if you had an array of strings and a pointer str
pointing into the array (to a string
) str 1
was the pointer to the next element of the array. If you want to handle the caracters of a string
with pointers you can do so with the c_str()
method of the string
void rec_rev_str_rec(char *str,int size){
if(size == 0){
return ;
}
swap(str[0],str[size]);
rec_rev_str_rec(str 1,size-2);//-2 because the first and the last elemenst are swapped
}
string rec_rev_str(string* s,int size){
rec_rev_str_rec(s->c_str(),size);
return s;
}
//or
string rec_rev_str2(string& s,int size){
rec_rev_str_rec(s.c_str(),size);
return s;
}