Search code examples
cstringtoken

removing spaces from a string in C language


I can't figure out how to remove the spaces at the beginning of the sentence without using any libraries other than stdio.h and stdlib.h.

#include <stdio.h>

int main()
{
   char text[1000], result[1000];
   int c = 0, d = 0;

   printf("Enter some text\n");
   gets(text);

   while (text[c] != '\0') { // till the end of the string
      if (text[c] == ' ') {  
         int temp = c + 1;   
         if (text[temp] != '\0') {  
            while (text[temp] == ' ' && text[temp] != '\0') { 
               if (text[temp] == ' ') { 
                  c++;                  
               }  
               temp++;                  
            }
         }
      }
      result[d] = text[c];
      c++;               
      d++;
   }
   result[d] = '\0';

   printf("Text after removing blanks\n%s\n", result);

   return 0;
}

This piece of code removes all the extra spaces of a sentence.

Example:

input: " this is my program."

output: " this is my program."

EXPECTED OUTPUT: "this is my program."

this code leaves only one space where there were more spaces, but I want to remove all spaces at the beginning as well like in the expected output.


Solution

  • #include <stdio.h>
    
    int main()
    {
       char text[1000], result[1000];
       int c = 0, d = 0;
    
       printf("Enter some text\n");
       gets(text);
    
       // no space at beginning
       while(text[c] ==' ') { c++; }
       while(text[c] != '\0'){
        result[d++] = text[c++]; //take non-space characters
        if(text[c]==' ') { result[d++] = text[c++]; } // take one space between words
        while(text[c]==' ') { c++; } // skip other spaces 
       }
       result[d] = '\0';
    
       printf("Text after removing blanks\n%s\n", result);
    
       return 0;
    }