Reverse words in a sentense keeping space positions same

Discussion in 'C' started by biswajit.dash, Jun 3, 2010.

  1. biswajit.dash

    biswajit.dash New Member

    Joined:
    Jul 31, 2007
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    I have been try this for 2-3 hr.

    what my intent is to hav program while will reverse the words in a sentence without changing the space positions.

    ex:

    input: char str[]="My name is Biswajit""
    output : "Biswajit is name My"

    I m successful in reversing the words without keeping the space positions same, i m not successful in other way.

    Appreciate any thoughts.

    Thx
    Biswajit
     
  2. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Scan right to left checking for spaces and counting the length of the word you're currently looking at.
    Then use strncpy to copy a fixed number of characters to the end of the output string.
    Remember to add spaces too.

    Another way to do it is to create a substring reverser that will reverse the specified characters within a string (for example, if you gave it "abcde", start position 1, number of characters 3, it would change the string to "adcbe"). Then reverse the whole string, and use the substring reverser to reverse each individual word.
     
  3. CrazyGeek

    CrazyGeek New Member

    Joined:
    Jun 6, 2010
    Messages:
    4
    Likes Received:
    0
    Trophy Points:
    0
    I think It's simpler if you use the function gotoxy(x,y);
    At first call gotoxy(x,y) to move text pointer to a position that the distance to home line is long enough to show your string.
    Then scan through all characters of your string and print one by one, if the charater is " " ( means a space), call gotoxy(x,y) to the appropriate position.( the text pointer must be back everytime you catch a space). I know you can understand my idea. OK thanks!
     
  4. xpi0t0s

    xpi0t0s Mentor

    Joined:
    Aug 6, 2004
    Messages:
    3,009
    Likes Received:
    203
    Trophy Points:
    63
    Occupation:
    Senior Support Engineer
    Location:
    England
    Good idea, except that gotoxy moves the cursor on the screen and has absolutely bu99er all to do with string manipulation.
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice