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;
}
The complete code is here. 9tKLCu - Online C Compiler & Debugging Tool - Ideone.com on which I tested it. Try using it.
1 Like