Reputation: 451
I wrote a program to reverse string where the string is a character array. The program is :
#include<iostream>
void rev(char *str)
{
char *end;
end = str;// end will now point to the same address of str
// now we need to incremet the end pointer upto it encounter null
if(str)// this checks if the string is present or not
{
while(*end)
++end;
--end;// set one character back, since last character is null
// swap characters from start of string with the end of the string
// until the pointers meet in middle.
while(str < end)
{
char temp = *str;
*str++ = *end;
*end-- = temp;
}
}
std::cout<<"\n The reversed string is : \n";
std::cout<<str<<std::endl;
}
int main()
{
char str[500];
std::cout<<"\n Enter the string : ";
std::cin.getline(str, sizeof(str));
rev(str);
return 0;
}
One output instance is :
Enter the string : asdfgh
The reversed string is :
dsa
I want to solve this problem inplace and using character array.
There are many solutions available on internet. I have seen them. But I want to know where I'm going wrong with this implementation. If there is some extra increment in str. I want to know how to correct it.
Upvotes: 0
Views: 495
Reputation: 1583
Well, the error is that you kept on increasing the str
pointer and after that decreasing the end
pointer, which finally met somewhere at the middle of the string. And right after, you printed out the string which starts somewhere from the middle in reverse order. So, I would suggest to do as follows:
#include<iostream>
void rev(char *str) {
char *end;
end = str;
if(str) {
while(*end)
++end;
--end;
while(str < end) {
char temp = *str;
*str++ = *end;
*end-- = temp;
}
}
/* Don't print the string here itself */
}
int main() {
char str[500];
std::cout<<"\n Enter the string : ";
std::cin.getline(str, sizeof(str));
rev(str);
/* Print your string here */
std::cout<<"\n The reversed string is : \n";
std::cout<<str<<std::endl;
return 0;
}
OUTPUT:
Enter the string : qwertyuiop
The reversed string is :
poiuytrewq
Upvotes: 4
Reputation: 76326
Well, since this is tagged c++, you should note that you can do this as
void rev(char* str)
{
std::reverse(str, str + strlen(str));
}
Looking at the documentation for std::reverse
you can deduce that it does it in place.
Upvotes: 3
Reputation: 775
Try this:
#include<bits/stdc++.h>
int main()
{
char str[500], revstr[500];
int i,j,len;
std::cout<<"\n Enter the string : ";
std::cin.getline(str, sizeof(str));
//reverse str
len = strlen(str);
for(i=len-1, j=0; i>=0; i--, j++){
revstr[j]=len[i];
}
revstr[j] = '\0'; //marks end of string
std::cout<<"\n The reversed string is : \n";
std::cout<<revstr<<std::endl;
return 0;
}
Upvotes: 0
Reputation: 16935
I think you're making the problem too confusing.
void reverse(char* s) {
// return if s is nullptr
if(!s) return;
size_t len = strlen(s);
// swap ith from front with ith from back
for(size_t i = 0; i < len/2; ++i) {
char temp = s[i];
s[i] = s[len - i - 1];
s[len - i - 1] = temp;
}
}
Upvotes: 5