22
Dec
Reverse Words in a String (In-Place)
Related Blog Items
- Palindrome Checker
- Print In Reverse-Order
- String Pattern Matching: Write a function that checks for a given pattern at the end of a given string
- String to Integer (atoi)
- i64toa - Converts a 64 bit integer to string
Here is a code snippet which can be used for reversing entire string/sentence or words in the the string/sentence. If you want to reverse a string entirely use delimiter as ‘\n’, if you want to reverse words use delimiter as ‘ ‘ space, or you can use any delimiter for custom reversing.
int reverse(char *string, char delimiter)
{
char *src, *dest;
char *temp = string;
while( *temp )
{
if (*temp == delimiter)
{
temp++;
continue;
}
src=dest=temp;
while ( (*(dest+1) != delimiter) &&
( *(dest+1) != '\n' ) &&
( *(dest+1) != '\0' )) dest++;
temp=dest+1;
while( dest > src )
{
char tmp = *dest;
*dest - - = *src;
*src++=tmp;
}
}
return 0;
}
int main()
{
char name[] = "OpenAsthra -- a formula pattern";
printf("%s\n",name);
reverse(name,' '); /* space as delimiter,Reverse Words */
printf("%s\n",name);
reverse(name,'\n'); /* Reverse Complete Sentence */
printf("%s\n",name);
}
download reversing words in string(in place) program [reverse_words.c]
Popularity: 38%
You need to log on to convert this article into PDF
Related Blog Items - Palindrome Checker
- Print In Reverse-Order
- String Pattern Matching: Write a function that checks for a given pattern at the end of a given string
- String to Integer (atoi)
- i64toa - Converts a 64 bit integer to string
Related Blog Items
- Palindrome Checker
- Print In Reverse-Order
- String Pattern Matching: Write a function that checks for a given pattern at the end of a given string
- String to Integer (atoi)
- i64toa - Converts a 64 bit integer to string
The program doesn’t give correct output. And if I am not wrong, C standard does not allow us to modify string literals and the result is undefined. Correct me if I am wrong.
August 8th, 2008 at 4:52 pm
I was wrong about the C standard thing. That was in case of string literals i.e. having pointers to point to a string constant. but, the program doesn’t give correct output anyway.
August 8th, 2008 at 4:59 pm