Remove extra blanks from a string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • afr02hrs
    New Member
    • Mar 2007
    • 2

    Remove extra blanks from a string

    Hi Experts

    I am trying to get the following program running correctly. I would like to be able to input a line of text containing multiple space characters between words and have the program remove any number of excess space characters so that the sentence is rewritten correctly containing only 1 space character between individual words. However this program outputs each word on a separate line! Is there a problem with my loop?

    Many thanks

    Code:
    int main(int argc, char **argv)
    {
     AnsiString Line;
     int Index;
    
    Line = ReadStringPr("Enter your text. It must not finish with a space character." );
    Index = 1;
    //read each char of Line
    
    while (Index <= Length(Line))
    {
       //if current char is not a space
       if (Line[Index] != ' ')//;
          {
          //write current char to screen
          WriteChar(Line[Index]);
          Index = Index + 1;
          }
       else //if current char is a space
          {
                WriteStringCr(' ');
          }
          //ignore all consecutive spaces
          while (Line[Index] == ' ')//;  this semicolon may have created an infinite loop not allowing anything to print to screen
            Index = Index + 1;
          
    } 
     getchar();  // to keep the display on until you press Enter key
     return 0;
     }
    Last edited by Ganon11; Mar 21 '07, 05:29 PM. Reason: code tags added
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    have you a } in the wrong place?
    Code:
    else //if current char is a space
    {
    WriteStringCr(' ');
    }  <<< should this
    //ignore all consecutive spaces
    while (Line[Index] == ' ')//; this semicolon may have created an infinite loop not allowing anything to print to screen
    Index = Index + 1;
    <<  be here????

    Comment

    • afr02hrs
      New Member
      • Mar 2007
      • 2

      #3
      Unfortunately moving this brace does not change anything. The words are still written one on each line and not as a corrected sentence. Braces seem to be the root of all evils!!

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        What is the difference between WriteChar() and WriteStringCr() ? Does one of them always output a newline character after execution?

        Comment

        Working...