Revesing a string

How can i reverse a string using the reverse() and reverse_copy() functions from <algorithm>? (i want to copy on a string the reverse of the first n characters of another sting)
Last edited on
1
2
3
4
5
string a = "forward";
string b = a;
reverse(b.begin(), b.end());

cout << b;  // "drawrof" 
Try these 2 functions :)



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int length(string word)
{
	int len=0;
	for(int i=0; word[i]!=NULL; i++)
		len++;
	return len;
}
void reverse(string word, int l)
{
	int j=0;
	string rev;
	for(int i=l-1; rev[i]>=0; i--)
		rev[j++]=word[i];
	rev[j]='\0';
	cout<<"The word after reversing --> "<<rev<<endl;
}
i want to copy on a string the reverse of the first n characters of another sting


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string>
#include <iostream>
#include <algorithm>
#include <cassert>
int main()
{
        std::string s1 = "Hello, world";
        std::string s2 = "Goodbye";
        unsigned int n = 5;
        assert(n < s1.size());
        assert(n < s2.size());

        reverse_copy(s2.begin(), s2.begin()+n, s1.begin());

        std::cout << s1 << '\n';
}
Last edited on
yes:) i figures it out know,
Firstly i need s1.assign(n,c);//c has any char in it
and then i can efficiently use: reverse_copy(s2.begin(), s2.begin()+n, s1.begin());
Thank you all :)
Topic archived. No new replies allowed.