简体   繁体   中英

Removing extra whitespaces from a string - C programming

The task is to remove all of the extra whitespaces in a string, for example if a string looks like this:

   volim      OR      

after the program is done it should look like this:

volim OR

so the program has to remove all the whitespaces before and after the strings, and those in between the words, so in the end there is just one between each word. This what I have so far :

#include <stdio.h>

char *IzbaciViskaRazmake (char *Str)
{
    char *p = Str;
    char *p2 = Str;
    while(*p!='\0')
    {
        if(*p==' ')
            p++;
        else if(*p!=' ')
        {
            *p2 = *p;
            p2++;
            p++;
        }
    }
    *p2='\0';
    return Str;
}

int main() {
    char tekst[] = "        volim      OR      ";
    IzbaciViskaRazmake(tekst);
    printf("'%s'",tekst);
    return 0;
}

The problem with my code is that it removes all of the whitespaces so it gives the output

volimOR

How can I repare my code, so it keeps the whitespaces between the words. PS- The use of pointers is a must.

You can do this by adding the first (whitespace) to *p2 and skipping the rest (whitespace) using a while-loop .

Try this modified code , This will work :-

#include <stdio.h>

char *IzbaciViskaRazmake(char *Str)
{
    char *p = Str;
    char *p2 = Str;
    while (*p != '\0')
    {
        if (*p == ' ')
        {
            if (*p != *Str) // Not begining
            {
                *p2 = *p; // adding the first ' '
                p2++;
                p++;
            }
            while (*p == ' ') // skipping the rest ' '
            {
                p++;
            }
        }
        else
        {
            *p2 = *p;
            p2++;
            p++;
        }
    }
    if (*(p2 - 1) == ' ') //ends with space
    {
        p2--;
    }
    *p2 = '\0';

    return Str;
}

int main()
{
    char tekst[] = "        volim      OR      ";
    IzbaciViskaRazmake(tekst);
    printf("'%s'", tekst);
    return 0;
}

Output :-

'volim OR'

Anoopknrs code gave me an idea how this code actually works, so I have managed to quickly fix it. Here is the fully working, hopefully it can help some other people.

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

    char *IzbaciViskaRazmake (char *Str)
    {
        char *p = Str;
        char *p2 = Str;
        while(*p!='\0')
        {
            if(*p==' ')
                p++;
            else if(*p!=' ')
            {
                *p2 = *p;
                p2++;
                p++;
                if(*p==' ')
                    {
                        *p2=*p;
                        p2++;
                        p++;
                    }
            }
        }
        *(p2-1)='\0';
        return Str;
    }

    int main() {
        char tekst[] = "        volim      OR      ";
        IzbaciViskaRazmake(tekst);
        printf("'%s'",tekst);
        return 0;
    }

I think you should divide this into three separate tasks:

  • Remove all whitespaces before first non-whitespace character
  • Remove all whitespaces after last non-whitespace character
  • Remove all whitespaces between words

This is three pretty separate tasks, and a reasonable assumption in your case seems to be to only count ' ' as whitespace. However, functions like this should i general return a NULL pointer on failure.

So we can declare this function:

char * trimSpaces(char *str) {
    if(!str) return NULL; // If we get a NULL pointer as input
    if((str = trimInitialSpaces(str)) == NULL) return NULL;
    if((str = trimEndingSpaces(str)) == NULL) return NULL;
    if ((str = trimSuperfluousSpaces(str)) == NULL) return NULL;
    return str;
}

Now you have three functions to write, but each of these is simpler than your original function.

The implementation of trimIntitialSpaces could then look like this:

char * trimInitialSpaces(char *str) {
    if(!str) return NULL;
    char * ptr = str;
    int len = strlen(str); // Get length of string                              
    if(len == 0) return str; // If len is 0, there's nothing to do
    while(*ptr == ' ' && *ptr != '\0') ptr++; // Find first non-space                               
    // memmove can handle overlapping arrays, which memcpy cannot               
    memmove(str, ptr, len-(ptr-str)+1);
    return str;
}

You have two functions left to write now. trimEndingSpaces(str) is slightly trickier, but all in all almost the same as trimInitialSpaces(str) . And then you only have trimSuperfluosSpaces(str) left, which is the trickiest one. But now you can debug all these three separate. Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM