separating a sentence into words

  • fish
  • Newbie
  • Newbie
  • fish
  • Posts: 5

Post 3+ Months Ago

Hi there,

I was after any suggestions as to how i could

-- accept a sentence from the user

-- then take each word from that sentence and display it in reverse order, but not reverse the order of the the whole sentence.

I was thinking to loop until '\0' - end of line
then within that loop, loop until i reach a ' '- space. when it reaches a space would I - create another function to reverse that word, then return back to the loop until the next space.

Hope what I've said makes sense!!

anyhelp would be greatly appreciated.

Thanks
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

If it was me what I would do is first take all the characters entered by the user and place it into an array. (If you printed the array in order you would get the sentece they typed).

Second I would then run a for loop on the array which would have another nested loop. The outer loop would start from the end of the array and work back to the beginning of the array. Once you find the first space on the outer loop then your inner loop would run from the current spot in the array and print out characters.

Note - you would probably need two counter variables. One to keep track of your starting position to print in the array, and a second to keep track of the ending position in the array in which you should print.

Anyway I am sure there are many ways in which you could achieve this, that is what I would try though.

Now if you can use C++ it would be much simplier. I would simply append all entered characters to a string. At that point I would just do a reverse find to find the spaces and split each word and place each word into an array, for which I could then just print the array backwards at that point.
  • fish
  • Newbie
  • Newbie
  • fish
  • Posts: 5

Post 3+ Months Ago

thanks for the help.

Could you please give me some idea how to code what you put in your post, as stated in an earlier thread I am a true 'NOVICE'.

thanks
  • fish
  • Newbie
  • Newbie
  • fish
  • Posts: 5

Post 3+ Months Ago

this is what i have so far but i cant work out how to put each word into a new array

Code: [ Select ]
int reverseWords()
{
    char whole_line[MAX_LINE];
    char word[MAX_LINE];
    int i;

    printf("%s", "\nEnter a line of text (upto 50 characters): \n");
    fgets(whole_line, MAX_LINE, stdin);

    for(i = 0; i < MAX_LINE, whole_line[i] !='\0'; i++)
    putchar(whole_line[i]);
    
    
    if(whole_line[i] == ' ')
    {
        strcpy(word, whole_line); <-- how can i pass in just the word and not the whole line???
        printf("word in if --> %s",word);
            }
        return 0;
}
  1. int reverseWords()
  2. {
  3.     char whole_line[MAX_LINE];
  4.     char word[MAX_LINE];
  5.     int i;
  6.     printf("%s", "\nEnter a line of text (upto 50 characters): \n");
  7.     fgets(whole_line, MAX_LINE, stdin);
  8.     for(i = 0; i < MAX_LINE, whole_line[i] !='\0'; i++)
  9.     putchar(whole_line[i]);
  10.     
  11.     
  12.     if(whole_line[i] == ' ')
  13.     {
  14.         strcpy(word, whole_line); <-- how can i pass in just the word and not the whole line???
  15.         printf("word in if --> %s",word);
  16.             }
  17.         return 0;
  18. }


thanks
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Instead of usign strcpy to copy characters from your whole_line try using strncpy as you can specify the exact length to copy. However you are going to have to figure out what the length is that you want to copy, which means you will need to compute the length of the word somehow. Anyway to learn more about strncpy check out this link:

http://www.cplusplus.com/ref/cstring/strncpy.html
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

Code: [ Select ]
/*
This is obviously too late to help the original poster, but I figure other people might view the topic and anyway I'm a bit rusty in C, so this seemed like a good problem to get back into it. This was my solution.
*/

#include <stdio.h>
#include <string.h>

int main(void)
{
int length,last,start = 0;
char c,string[100];

printf("Enter a string: ");
gets(string);

length = strlen(string)+1;

    for(int i=0; i<length; i++)
    {
        c = string[i];

        if(c == ' ' || c=='\0')
        {
            last = i-1;

            for(int j=0; j<i-start; j++)
            {
                putchar(string[last--]);
            }
            if(c!='\0')
            {
                putchar(' ');
            }

            start = i+1;
        }
    }
return 0;
}
  1. /*
  2. This is obviously too late to help the original poster, but I figure other people might view the topic and anyway I'm a bit rusty in C, so this seemed like a good problem to get back into it. This was my solution.
  3. */
  4. #include <stdio.h>
  5. #include <string.h>
  6. int main(void)
  7. {
  8. int length,last,start = 0;
  9. char c,string[100];
  10. printf("Enter a string: ");
  11. gets(string);
  12. length = strlen(string)+1;
  13.     for(int i=0; i<length; i++)
  14.     {
  15.         c = string[i];
  16.         if(c == ' ' || c=='\0')
  17.         {
  18.             last = i-1;
  19.             for(int j=0; j<i-start; j++)
  20.             {
  21.                 putchar(string[last--]);
  22.             }
  23.             if(c!='\0')
  24.             {
  25.                 putchar(' ');
  26.             }
  27.             start = i+1;
  28.         }
  29.     }
  30. return 0;
  31. }
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

Code: [ Select ]
/*
If you were supposed to modify the original string by reversing the interior strings without reversing the whole thing, then I would do it like this.
*/

#include <stdio.h>
#include <string.h>

int main(void)
{
int length,start = 0,last,first;
char c,temp,string[100];

printf("Enter a string: ");
gets(string);

length = strlen(string)+1;

    for(int i=0; i<length; i++)
    {
        c = string[i];

        if(c == ' ' || c=='\0')
        {
            last=i-1;
            first=start;
            for(int j=0; j<(i-start)/2; j++)
            {
                temp = string[first];
                string[first] = string[last];
                string[last] = temp;
                last--;
                first++;
            }
            start = i+1;
        }
    }
printf("%s\n",string);
return 0;
}
  1. /*
  2. If you were supposed to modify the original string by reversing the interior strings without reversing the whole thing, then I would do it like this.
  3. */
  4. #include <stdio.h>
  5. #include <string.h>
  6. int main(void)
  7. {
  8. int length,start = 0,last,first;
  9. char c,temp,string[100];
  10. printf("Enter a string: ");
  11. gets(string);
  12. length = strlen(string)+1;
  13.     for(int i=0; i<length; i++)
  14.     {
  15.         c = string[i];
  16.         if(c == ' ' || c=='\0')
  17.         {
  18.             last=i-1;
  19.             first=start;
  20.             for(int j=0; j<(i-start)/2; j++)
  21.             {
  22.                 temp = string[first];
  23.                 string[first] = string[last];
  24.                 string[last] = temp;
  25.                 last--;
  26.                 first++;
  27.             }
  28.             start = i+1;
  29.         }
  30.     }
  31. printf("%s\n",string);
  32. return 0;
  33. }
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

Code: [ Select ]
/*
As bigwebmaster pointed out it's a lot easier in an OOP language that has a string data type. Here's the second version in java w/out user input.
*/

import java.util.StringTokenizer;
public class Test
{
    public static void main(String[] args){
        String strings = "one two three four five six seven";
        StringTokenizer chopper = new StringTokenizer(strings);
        strings = "";
        while(chopper.hasMoreTokens()){
            strings += new StringBuffer(chopper.nextToken()).reverse().toString();
            strings +=" ";
        }
        strings = strings.trim();
        System.out.println(strings);
    }
}
  1. /*
  2. As bigwebmaster pointed out it's a lot easier in an OOP language that has a string data type. Here's the second version in java w/out user input.
  3. */
  4. import java.util.StringTokenizer;
  5. public class Test
  6. {
  7.     public static void main(String[] args){
  8.         String strings = "one two three four five six seven";
  9.         StringTokenizer chopper = new StringTokenizer(strings);
  10.         strings = "";
  11.         while(chopper.hasMoreTokens()){
  12.             strings += new StringBuffer(chopper.nextToken()).reverse().toString();
  13.             strings +=" ";
  14.         }
  15.         strings = strings.trim();
  16.         System.out.println(strings);
  17.     }
  18. }
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

Code: [ Select ]
/*
I may have misunderstood the problem
the above examples take a string like "one two three" and output "eno owt eerht"
to get "three two one" I came up with this and it seemed to work
*/

#include <stdio.h>
#include <string.h>

int main(void)
{
    int length,letter;
    char c,string[100];

    printf("Enter a string: ");
    gets(string);

    length = strlen(string);

    for(int i=length; i>=0; i--)
    {
        c = string[i];
        
        if(c == ' ' || i==0)
        {
            if(i==0)
            {
                letter = i;
            }
            else
            {
                letter = i+1;
            }
            c=string[letter];
            while((c !='\0') && (c !=' '))
            {
                putchar(string[letter]);
                letter++;
                c=string[letter];
            }
            if(i!=0)
            {
                putchar(' ');
            }
        }
    }
    return 0;
}
  1. /*
  2. I may have misunderstood the problem
  3. the above examples take a string like "one two three" and output "eno owt eerht"
  4. to get "three two one" I came up with this and it seemed to work
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. int main(void)
  9. {
  10.     int length,letter;
  11.     char c,string[100];
  12.     printf("Enter a string: ");
  13.     gets(string);
  14.     length = strlen(string);
  15.     for(int i=length; i>=0; i--)
  16.     {
  17.         c = string[i];
  18.         
  19.         if(c == ' ' || i==0)
  20.         {
  21.             if(i==0)
  22.             {
  23.                 letter = i;
  24.             }
  25.             else
  26.             {
  27.                 letter = i+1;
  28.             }
  29.             c=string[letter];
  30.             while((c !='\0') && (c !=' '))
  31.             {
  32.                 putchar(string[letter]);
  33.                 letter++;
  34.                 c=string[letter];
  35.             }
  36.             if(i!=0)
  37.             {
  38.                 putchar(' ');
  39.             }
  40.         }
  41.     }
  42.     return 0;
  43. }
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Very nice, I think this additional info could prove useful for some :)
  • UNFLUX
  • Genius
  • Genius
  • User avatar
  • Posts: 6376
  • Loc: twitter.com/unflux

Post 3+ Months Ago

doesn't mean a thing to me. I expected to see sentences, and all I see is a
bunch of symbols and letters and characters and stuff... :P
  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

Code: [ Select ]
/*
I hope you mean that the code looks like gibberish and not that you ran the code and the result was gibberish. Anyway, here is the first version properly commented - the others versions are just variations on the same theme - except for java which is a horse of a different color.
*/
#include <stdio.h>
#include <string.h>

int main(void)
{
int length,last,start = 0;
char c,string[100];

//prompt the user and input the string
printf("Enter a string: ");
gets(string);

//get the string's length and add 1 for the null terminator - '\0'
length = strlen(string)+1;

    //the outer loop will "walk" over the whole string
  for(int i=0; i<length; i++)
  {
      //extract a letter each "step"
   c = string[i];
     
     //if the letter is a space or the null terminator start reversing
   if(c == ' ' || c=='\0')
   {
         //"i" will point to the space between the words or the '\0' at the end
         //of the sentence so go back one for the last letter of the word
     last = i-1;
        
         //start will be 0 the first time so i-start will hold the length
         //that we need to reverse and we will change start afterwards
     for(int j=0; j<i-start; j++)
     {
             //put the letter to the output and step back one each time
      putchar(string[last--]);
     }
     if(c!='\0')
     {
             //since we "stepped back over" the space we need to replace it
             //between words but not after the last word that ends in '\0'
      putchar(' ');
     }
         //we didn't change "i" itself so it still points to the space
         //now we add one to "i" to save the start position of the next word
     start = i+1;
   }
  }
return 0;
}
  1. /*
  2. I hope you mean that the code looks like gibberish and not that you ran the code and the result was gibberish. Anyway, here is the first version properly commented - the others versions are just variations on the same theme - except for java which is a horse of a different color.
  3. */
  4. #include <stdio.h>
  5. #include <string.h>
  6. int main(void)
  7. {
  8. int length,last,start = 0;
  9. char c,string[100];
  10. //prompt the user and input the string
  11. printf("Enter a string: ");
  12. gets(string);
  13. //get the string's length and add 1 for the null terminator - '\0'
  14. length = strlen(string)+1;
  15.     //the outer loop will "walk" over the whole string
  16.   for(int i=0; i<length; i++)
  17.   {
  18.       //extract a letter each "step"
  19.    c = string[i];
  20.      
  21.      //if the letter is a space or the null terminator start reversing
  22.    if(c == ' ' || c=='\0')
  23.    {
  24.          //"i" will point to the space between the words or the '\0' at the end
  25.          //of the sentence so go back one for the last letter of the word
  26.      last = i-1;
  27.         
  28.          //start will be 0 the first time so i-start will hold the length
  29.          //that we need to reverse and we will change start afterwards
  30.      for(int j=0; j<i-start; j++)
  31.      {
  32.              //put the letter to the output and step back one each time
  33.       putchar(string[last--]);
  34.      }
  35.      if(c!='\0')
  36.      {
  37.              //since we "stepped back over" the space we need to replace it
  38.              //between words but not after the last word that ends in '\0'
  39.       putchar(' ');
  40.      }
  41.          //we didn't change "i" itself so it still points to the space
  42.          //now we add one to "i" to save the start position of the next word
  43.      start = i+1;
  44.    }
  45.   }
  46. return 0;
  47. }
  • wynpublishing
  • Newbie
  • Newbie
  • User avatar
  • Posts: 5

Post 3+ Months Ago

Or in VBscript:

Code: [ Select ]
Dim vArray
  Dim iWords
  Dim sSentence
  Dim i
  Dim x
  Dim sWord
  Dim sWordReversed
  Dim sNewSentence
  sSentence = "This is a sentence with four words"
  
  vArray = Split(sSentence, " ")
  iWords = UBound(vArray)
  For i = 0 To iWords
    sWord = vArray(i)
    Do
      sWordReversed = sWordReversed & Right(sWord, 1)
      sWord = Left(sWord, Len(sWord) - 1)
    Loop Until Len(sWord) = 0 'Loop until the length of x is zero.
    sNewSentence = sNewSentence & sWordReversed & " "
    Debug.Print vArray(i)
    Debug.Print sWordReversed
    Debug.Print sNewSentence
    sWordReversed = ""
    sWord = ""
  Next
  Erase vArray
  1. Dim vArray
  2.   Dim iWords
  3.   Dim sSentence
  4.   Dim i
  5.   Dim x
  6.   Dim sWord
  7.   Dim sWordReversed
  8.   Dim sNewSentence
  9.   sSentence = "This is a sentence with four words"
  10.   
  11.   vArray = Split(sSentence, " ")
  12.   iWords = UBound(vArray)
  13.   For i = 0 To iWords
  14.     sWord = vArray(i)
  15.     Do
  16.       sWordReversed = sWordReversed & Right(sWord, 1)
  17.       sWord = Left(sWord, Len(sWord) - 1)
  18.     Loop Until Len(sWord) = 0 'Loop until the length of x is zero.
  19.     sNewSentence = sNewSentence & sWordReversed & " "
  20.     Debug.Print vArray(i)
  21.     Debug.Print sWordReversed
  22.     Debug.Print sNewSentence
  23.     sWordReversed = ""
  24.     sWord = ""
  25.   Next
  26.   Erase vArray
  • UNFLUX
  • Genius
  • Genius
  • User avatar
  • Posts: 6376
  • Loc: twitter.com/unflux

Post 3+ Months Ago

oh, to be a coder...*sigh*
  • baby_eye_26
  • Born
  • Born
  • baby_eye_26
  • Posts: 2

Post 3+ Months Ago

what changes do i have to make if i need to read from a text file that contains lines of text to be reversed and also use malloc() & free()? There also has to be output of the reversed text.

Eg: Good morning!

3-2 = 1;

After reverse:
morning! Good

1; = 3-2

Can anybody help me?Thanks....
  • Bigwebmaster
  • Site Admin
  • Site Admin
  • User avatar
  • Posts: 9089
  • Loc: Seattle, WA & Phoenix, AZ

Post 3+ Months Ago

Okay so let me get this straight. You want to reverse the words and not the text per line? because if it was the text you were wanting reversed on each line it would look something like:

!gninrom dooG

;1 = 2-3

and if you wanted just the words reversed (ie things seperated by spaces) it would look something like:

morning! Good

1; = 3-2

There is a big difference, so I just want to clarify this.
  • baby_eye_26
  • Born
  • Born
  • baby_eye_26
  • Posts: 2

Post 3+ Months Ago

sorry...i want to reverse the line...that means if input is Good morning!, the output should be morning! Good...
  • £het®
  • Newbie
  • Newbie
  • User avatar
  • Posts: 5

Post 3+ Months Ago

oh ok... If I were to do this, i'll make it this way... in php hehehehe :D

1. pass the lines/sentences as array either by using explode, etc.
2. pass each word as array.
3. loop from max to 0 of each array starting from the word array

for the simplest start:
Code: [ Select ]
$str = "This is the whole sentence";

$word = split(' ',$str);

for($i=count($word);$i>=0;$i--){
    echo $word[$i]." ";
}
  1. $str = "This is the whole sentence";
  2. $word = split(' ',$str);
  3. for($i=count($word);$i>=0;$i--){
  4.     echo $word[$i]." ";
  5. }

Post Information

  • Total Posts in this topic: 18 posts
  • Users browsing this forum: No registered users and 151 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.