String - Reverse @ same place :-

how to reverse a string without changing its place ?
eg - input: welcome to codechef website
output: emoclew ot fehcedoc etisbew

@amitcom :

Let char[] str have the string and len be its length .

To reverse

for(int i = 0 ; i < len/2 ; i++) {

char c = str[i];

str[i] = str[len-1-i];

str[len-1-i] = c;

}

int start =0;
int i=0;
int end = 0;
int j=0;
int k=0;
char temp;
while(i<strlen(str))
{
while(str[i]!=’ ’ && str[i]!=’\0’)
{
i++;
}
end = i-1;
j= start;
k = end;
while(j<k)
{
temp = str[j];
str[j]=str[k];
str[k]= temp;
j++;
k–;
}
i++;
start = i;
}

Try this. Part by part the code is trying to reverse the string.

2 Likes

char *b = &str[0];
char e = b + strlen(str) - 1;
while(b < e) {
/
Swap characters */
const char temp = *b;
*b++ = *e;
*e-- = temp;
}

its not working …@vermashubhang

The complete code is here. 9tKLCu - Online C Compiler & Debugging Tool - Ideone.com on which I tested it. Try using it.

1 Like

Thanx a lot …@vermashubhang

@amitcom If you are satisfied accept the solution so that the question could be closed.

@vermashubhang i don’t know how to accept solution …m new here

@amitcom Just click the tick mark beside the answer below the vote down button.