views:

130

answers:

2
void RemoveSpace(char *String)
{
    int i=0,y=0;
    int leading=0;

    for(i=0,y=0;String[i]!='\0';i++,y++)
    {
        String[y]=String[i];    // let us copy the current character.

        if(isspace(String[i]))  // Is the current character a space?
        {
            if(isspace(String[i+1])||String[i+1]=='\0'||leading!=1) // leading space
                y--;
        }
        else
            leading=1;
    }
    String[y]='\0';
}

Does this do the trick of removing leading and trailing whitespaces and replacing multiple whitespaces with single ones ?? i tested it for null string, all whitespaces, leading whitespaces and trailing whitespaces.

Do you think this is an efficient one pass solution ??

+3  A: 
string Replace(string strText)
{
    Regex regEx = new Regex("\\s+", RegexOptions.Multiline);
    return strText = Regex.Replace(strText, " ");
}

Should do the trick.

Ardman
I am looking for something in C ..
Phoenix
Have just added the C language into the tags.
Ardman
+1  A: 

based on your code, assume your iswhite() is efficient, (which you might not make it separate, as it is called too frequent) assume the passed in string is valid itself (should be more defensive)

=======================

void RemoveSpace(char *String) {

int i=0, j=0;

int inWhite=0;

char c = String[i++];
while(c)
{
    if (isspace(c))
    {
        inWhite= 1;
    }
    else
    {
        // there are space before, and not beginning
        if (inWhite && j > 0)
        {
            String[j++] = " ";
        }
        String[j++] = c;
        inWhite = 0;
    }

    c = String[i++];
}
String[j]='\0';

}

not tested, please test yourself...

ccppjava