Saturday, December 31, 2011

Remove whitespace from a string in-place, in linear time


void removeWhitespace(char* str) {
    int current = 0;
    int ahead = 0;
 
    while (str[ahead] != '\0') {
        while (str[ahead] == ' ') ahead++;
 
        str[current] = str[ahead];
        current++;
        ahead++;
    }
}

2 comments:

  1. Should not there be a \o in the end to terminate the string??

    ReplyDelete
    Replies
    1. Yes this is a '\0' terminated string only. We are moving ahead only when we find a white space (when we say):
      while (str[ahead] == ' ') ahead++;

      Rest all the characters except the space are copied as is, which also includes '\0' and hence string is '\0' . Please let me know if you don't agree with me. :)

      Delete