Reverse a String

Write a simple code to reverse a string.

INPUT: "HELLO WORLD"
OUTPUT: "DLROW OLLEH"

The logic to reverse a string is simple, swap the first character with last character, the second character with the second-last character and so on...

Take two variables low and high to hold the indices of first and last element, increment low and decrement high as long as low<high.

CODE:

void reverse(char* str, int n) 
{
if(str == NULL || n <= 1)
return;
int low = 0;
int high = n-1;

while(low < high)
{
char temp = str[low];
str[low] = str[high];
str[high] = temp;
low++;
high--;
}
}

The code traverse the string only once and takes O(n) time.

Tags:

String Reverse

0 Comments

Leave a comment