Search

Sponsored Links

Meta

Categories

Archives

Recent Posts

RSS Feeds

22
Dec

Reverse Words in a String (In-Place)

Related Blog Items

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

2 Comments

  • Swapnil  said:

    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.


  • Swapnil  said:

    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.


Leave a comment

*
To prove you're a person (not a spam script), type the security word shown in the picture.
Anti-spam image