Tuesday, May 28, 2013

Remove Extra white spaces from the given string


Suppose you are given a string with more than one space between two words. You are supposed to remove these extra spaces .
For doing this , i have implemented two methods .

In the first method , there is flag called x , that denotes whether a space is already encountered or not . If yes , x is set to 1 or else it is set to 0

In the second method , I copied each element from the input string to the output string except for the condition that when two consecutive spaces occurs . If two consecutive spaces occur , it just iterates forward , until a non-space character is found .The process repeats for all the characters in the input string .


// program to trim two or more blanks in the given string

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

char *trimBlank1(char *str)
{
    int i = 0 ,x = 0 , j =0;
    char *newString = (char *)malloc(sizeof(strlen(str)));

    while(str[i] != '\0')
    {
        if(str[i] == ' ' && x == 0)
            x = 1 ;
        else if(str[i] == ' ' && x == 1)
        {
            i++;
            continue;
        }
        else if (str[i] != ' ')
                x = 0 ;

        newString[j++] = str[i++] ;
    }
    newString[j] = '\0';
    printf("\nMethod 1 : %s",newString);
    return newString ;
}

void trimBlank2(char *is , char *os)
{
    int i = 0 , j = 0;

    while(i < strlen(is))
    {
        os[j++] = is[i++];

        while(is[i] == ' ' && is[i+1]==' ')
            i++;
    }

    os[j]='\0';
    printf("\nMethod 2 : %s",os);
}


int main()
{
    char input[100] , output[100];

    printf("\nEnter the input string:");

    gets(input);
    printf("\nBefore trimming:%s",input);
    printf("\nAfter trimming : %s",trimBlank1(input));

    printf("\n\nBefore Trimming: %s",input);
    trimBlank2(input,output);
    printf("\nAfter Trimming : %s",output);
    printf("\n\n");

    return 0;
}