Time spent here:

Sunday, 10 April 2016

how to remove spaces from a given string

solution:

1) Initialize 'count' = 0 (Count of non-space character seen so far)
2) Iterate through all characters of given string, do following
     a) If current character is non-space, then put this character
        at index 'count' and increment 'count'
3) Finally, put '\0' at index 'count'

c implementation:

#include <stdio.h>

int main()
{
    char str[100]="wel     come       ";
    int count=0;
    for(int i=0;str[i];i++)
    {
        if(str[i] != ' ')
          str[count++]=str[i];
    }
   str[count] = '\0';
   printf("%s",str);
    return 0;
}

output:



No comments:

Post a Comment