satyam jha
satyam jha

Reputation: 23

Remove extra space in string in C without using any predefined functions

I want to remove extra spaces in string in C without using any predefined function.
Here is my code:
but still after XYZ one extra space is printing.
Is there any better approach please share

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

int main() {
    char str[30] = "   abcdef   abc   xyz   ";
    int l = strlen(str),n=0;
    printf("(");                // added for clarity
    for(int i=0;i<l;i++)
    {
        if(str[i]==' ')
        {
            n++;
            if(i==0 || i==l-1)
            {
                continue;
            }
            else
            {
                if(n>1)
                {
                    continue;
                }
                else{
                    printf("%c",str[i]);
                }
            }
        }
        else{
            n=0;
            printf("%c",str[i]);
        }
    }
    printf(")\n");             // added for clarity
    return 0;
}

Program output is

(abcdef abc xyz )

Expected output is

(abcdef abc xyz)

Upvotes: 0

Views: 700

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311118

Your program always outputs a space each time when n is equal to 1 and i is not equal to 0 or l-1. So one trailing space (if there are at least two trailing spaces) will be always outputted.

Also numerous continue statements make your code too complicated.

And using the standard string function strlen is redundant.

Always try to write a more general code. That is you could write a separate function that could be called for any string to output it.

Here is a demonstration program.

#include <stdio.h>

void output_string( const char *s )
{
    int space = 0;

    for ( ; *s != '\0'; ++s )
    {
        if (*s != ' ')
        {
            if (space) putchar( ' ' );

            putchar( *s );

            space = s[1] == ' ';
        }
    }
}

int main( void )
{
    putchar( '(' );
    output_string( "   abcdef   abc   xyz   " );
    printf( ")\n" );
}

The program output is

(abcdef abc xyz)

The function can be more general if to include processing of tab character '\t'.

To do so it is enough to include header <ctype.h> and change this statement

space = s[1] == ' ';

to

space = isblank( ( unsigned char )s[1] );

As you can see the function has no continue statements. You should avoid using the continue statement if possible. In general using the continue statement makes programs less readable.

Upvotes: 3

0___________
0___________

Reputation: 68014

  1. Use functions.
  2. There is no ned of calling strlen
  3. The type of l is wrong (should be size_t)
char *trimAndStrip(char *str, char ch)
{
    char *head = str, *tail = str;
    if(str)
    {
        while(*tail == ch) tail++;
        while(*tail)
        {
            if(*tail != ch) *head++ = *tail++;
            else 
            {
                *head++ = *tail++;
                 while(*tail == ch) tail++;
            }
        }
    
        if(head > str && *head == ch) head--;
        *head = 0;
    }
    return str;
}

int main(void)
{
    char str[] = "   abcdef   abc   xyz   ";
    char str1[] = "abcdefxyz";
    char str2[] = "       ";
    char str3[] = "";

    printf("\"%s\"\n", trimAndStrip(str, ' '));
    printf("\"%s\"\n", trimAndStrip(str1, ' '));
    printf("\"%s\"\n", trimAndStrip(str2, ' '));
    printf("\"%s\"\n", trimAndStrip(str3, ' '));
}

Upvotes: 1

Hogan
Hogan

Reputation: 70538

The goal of your code is to do two things.

  1. If there is more than one space between words print only one space.
  2. If there are spaces at the start or the end remove all those spaces.

The logic of your program handles 1) fine. It also hands spaces at the start fine. However, it does not handle spaces at the end. This is because you don't know at the start of a sequence of spaces if it is an ending sequence, so you print the space before you know it is the ending sequence.

The best way to solve this problem is to "pre-process" That is look at the string before the loop and find the first non space character. And look at the string and find the last non space character (started at the end and going backwards.)

Now you can process the characters from the starting location to that ending location using the algorithm you have shown and it will work.

Hat tip: @weather vane's comment, which says the same thing but does not explain as much as this answer.

Upvotes: 3

Related Questions