Thread: Reversing a sentence.

  1. #1
    Registered User
    Join Date
    Feb 2003
    Posts
    175

    Reversing a sentence.

    Just wodering C code for reversing a sentence. I searched at this board but could not find it. Anybody knows where else can I find it?

    For example.
    If I input,

    change is truth of life

    output should be

    life of truth is change

    Please let me know.

  2. #2
    Banned
    Join Date
    Aug 2004
    Posts
    5
    Break it down into steps:

    Read in the sentence
    Identify were the words change
    reverse them

    functions that might help:
    fgets()
    strtok()

    Other hints:
    Using multiple arrays
    Possibliy using a link list to store the location of each of the words after strtok()

  3. #3
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    Do a board search

  4. #4
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    You might want to look up the strlen function as well, that could come in handy.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Using multiple arrays
    Why? This can be done inplace.

    >Possibliy using a link list to store the location of each of the words after strtok()
    Overkill. The inplace algorithm is shorter and easier to understand.

    >Do a board search
    He said he already did even though I know this question has be posed many times before. I've answered it quite a bit that I can remember.

    >You might want to look up the strlen function as well, that could come in handy.
    Maybe. My implementation didn't require any string.h functions at all.

    >Just wodering C code for reversing a sentence.
    Is this homework? If so, coming up with your own solution would be a much better use of your time. Here's a hint: Reverse the entire sentence first, then walk along the reversed sentence marking the beginning and end of each word and reverse those. The end result will be what you want. A quick paper run works as proof:

    change is truth of life
    efil fo hturt si egnach
    life fo hturt si egnach
    life of hturt si egnach
    life of truth si egnach
    life of truth is egnach
    life of truth is change

    Now for the easy part, writing an implementation in C.
    My best code is written with the delete key.

  6. #6
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    Quote Originally Posted by Prelude
    He said he already did even though I know this question has be posed many times before. I've answered it quite a bit that I can remember.
    I am aware that the OP claimed to have done a board search, but seriously, what were the search terms? They could not have been 'reverse a string' or 'reversing a string'



    ~/

  7. #7
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >but seriously, what were the search terms?
    The same as everyone else who claims that a search was fruitless: "solve my problem for me"
    My best code is written with the delete key.

  8. #8
    Registered User
    Join Date
    Feb 2003
    Posts
    175
    Here you go...

    Any changes/optimizations are welcome...

    Code:
    #include<stdio.h>                          
    #include<conio.h>
    #include<string.h>
    #include<stdlib.h>
    
    
    #define DELIM   ' '
    #define NLINE	'\n'
    
    #define EXCHANGE(a,b)	\
    					a = a^b; \
    					b = b^a; \
    					a = a^b; 
    
    void my_reverse(char *p,char *q);
    
                     
    int main(void)                             
    {
    	char string[100];
    	char *p,*walk;
    
    	printf("Enter a string: ");
    	fflush(stdout);
    
    	if ( fgets(string,sizeof(string),stdin) != NULL )
    	{
    		if ( ( p = strchr(string,'\n')) != NULL )
    			printf("\n<%s>",string);
    		else
    			exit(1);
    	}
    	else
    	{
    	printf("Error\n");
    		exit(1);
    	}
    
    	my_reverse(string,(p-1));
    	printf("\n<%s>",string);
    
    	walk = string;
    	while ( walk < p )
    	{
    		char *sep;
    		if ( ( (sep = strchr(walk,DELIM)) != NULL ) || ( (sep = strchr(walk,NLINE)) != NULL ) )
    		{
    			my_reverse(walk,sep-1);
    			while( sep++ == DELIM )
    				;
    			walk = sep;
    		}
    		else
    			break;
    	}
    	printf("\n<%s>",string);
    	return 0;	
    }
    
    
    void my_reverse(char *p,char *q)
    {
    	int i;
    	
    	i = (q-p);
    
    	if (i%2)
    		i = i/2+1;
    	else
    		i = i/2;
    
    	while ( i-- )
    	{
    		EXCHANGE(*p,*q);
    		p++;
    		q--;
    	}
    }

  9. #9
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Code:
    itsme@dreams:~/C$ cat strrev.c
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int main(int argc, char **argv)
    {
      char buf[4096], *p;
      size_t len;
    
      if(argc != 2)
      {
        puts("Usage: strrev <message>");
        exit(EXIT_FAILURE);
      }
      if((len = strlen(argv[1])) >= sizeof(buf))
      {
        puts("Message too long!");
        exit(EXIT_FAILURE);
      }
    
      strcpy(buf, argv[1]);
      for(p = buf+len;p >= buf;--p)
        if(*p == ' ')
        {
          *p = '\0';
          printf("%s ", p+1);
        }
      puts(p+1);
    
      return 0;
    }
    itsme@dreams:~/C$ ./strrev 'I think this code is a bit more understandable'
    understandable more bit a is code this think I
    EDIT: Changed len to type size_t
    Last edited by itsme86; 08-29-2004 at 08:12 PM.
    If you understand what you're doing, you're not learning anything.

  10. #10
    Registered User
    Join Date
    Jun 2003
    Posts
    51
    is there any possible to solve it using recursion and without string.h?

    i tried to solve using recursion, but failed.

  11. #11
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    #define EXCHANGE(a,b)\
    a = a^b; \
    b = b^a; \
    a = a^b;
    This a really bad way to do a swap. Search the boards and you'll find plenty of threads discussing it.

  12. #12
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    Code:
    $ cat strrev2.c
    #include <stdio.h>
    
    void rev_it(char *str)
    {
      char *s;
      char buf[100], *b;
    
      for(s = str, b = buf;*s && *s != ' ';s++, b++)
        *b = *s;
      *b = '\0';
    
      if(*s)
        rev_it(s+1);
      printf("%s ", buf);
    }
    
    int main(void)
    {
      char *str = "reverse this thing for me";
    
      rev_it(str);
      printf("\n");
    
      return 0;
    }
    $ ./strrev2
    me for thing this reverse
    Please ask if you have any questions on why/how that works. It's important for you to understand the concept of recursive functions.
    Last edited by itsme86; 08-30-2004 at 12:35 AM.
    If you understand what you're doing, you're not learning anything.

  13. #13
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Meh I'm bored so here goes:
    It uses an in place solution and pretty much does exactly what Prelude said, reverse the entire thing and then reverse each word. It avoids using an extra array and avoids using recursion since IMO recursion is not the best for this.
    Code:
    #include <stdio.h>
    #include <string.h>
    
    char * wordBasedStringRev(char *, int);
    char * myStringRev(char *, char *);
    void swap (char *, char *);
    
    int main(void)
    {
      char arr[] = "Hello my name is Thantos how are you today";
      puts("Before");
      puts(arr);
      wordBasedStringRev(arr, sizeof arr -1);
      puts("After");
      puts(arr);
      return 0;
    }
    
    char * wordBasedStringRev(char *str, int len)
    {
      char *p=str, *q=NULL;
      myStringRev(str, str+len-1);
      while ( (q = strchr (p, ' ')) != NULL)
      {
        myStringRev(p,q-1);
        p = q + 1;
      }
      myStringRev(p, (str+len)-1);
      return str;
    }
    
    char * myStringRev(char *beg, char *end)
    {
      int offset;
      for ( offset = 0; offset < ((end - beg) / 2)+1; offset++)
        swap (beg+offset, end-offset);
    
      return beg;
    }
    
    void swap (char *a, char *b)
    {
      char c = *a;
      *a = *b;
      *b = c;
    }

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Roaring_Tiger
    Just wodering C code for reversing a sentence. I searched at this board but could not find it. Anybody knows where else can I find it?
    You did huh? Are you sure about that?

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reversing Letters in Words of a Sentence
    By CRSpeedy in forum C Programming
    Replies: 10
    Last Post: 03-31-2009, 06:12 PM
  2. vector<...>::iterators and insert - I'm stumped.
    By Dino in forum C++ Programming
    Replies: 6
    Last Post: 12-25-2007, 06:11 AM
  3. Random Sentence From A File
    By gandil in forum C Programming
    Replies: 3
    Last Post: 01-08-2006, 09:50 AM
  4. mafia game
    By italiano40 in forum Game Programming
    Replies: 7
    Last Post: 11-07-2005, 01:22 AM
  5. Searching for words within a sentence
    By drdroid in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:09 AM