Reversing a String in C
Two examples of reversing a string: one using malloc to allocate memory for a string and the other using only a single character space.
|
char* reverseStr1( char* str )
{
char *ptr;
int len, i;
|
len = strlen( str ); | // Find length of string |
ptr = malloc( sizeof( char ) *( len+1 ) ); | // Allocate memory for new string |
for( i = len-1; i >= 0; i-- ) { | // start at end of string and move back |
*( ptr+len-i-1 ) = *( str+i ); | // put last letter into first position of new string |
} | // then next in succesion etc. |
*( ptr+len ) = '\0'; | // Add end of string character to end of new string |
return ptr;
}
void reverseStr2( char* str )
{
int i, j, len;
char tmp;
i = j = len = tmp = 0;
|
len = strlen( str ); | // Find length of string |
for ( i = 0, j = len-1; i <= j; i++, j-- ) { | // Start at end of string and move back |
tmp = str[ i ]; | // For the first iteration of the loop:- // store first letter |
str[ i ] = str[ j ]; | // put last letter of old string into first position of new |
str[ j ] = tmp; | // put stored first letter into last position of new string // then next in succesion etc. |
}
}
|
Return to Top
c-cpp index
Main Index
(c) Compiled by B V Wood.
|