Tuesday, August 14, 2012

Remove white spaces in a string in one pass O(n) time

// INPUT : how    are   you  ?
//OUTPUT : howareyou?

#include<stdio.h>
#define MAX 1024

void removeSpaces(char *str){
int i=0,j=0;
while(str[i] != '\0'){
if(str[i] != ' '){
str[j] = str[i];
j++;
}
i++;
}
str[j] = '\0';
}

int main(){
char str[MAX];
fgets(str,MAX,stdin);
printf("%s\n",str);
removeSpaces(str);
printf("%s\n",str);
return 0;
}

No comments:

Post a Comment