C program to trim leading and trailing white spaces from a string

In this blog post, you will learn how to write a C program to trim leading and trailing white spaces from a string. How to remove both leading and trailing white space characters in a string using loop in C programming. Also, logic to delete all leading and trailing white space characters from a given string in C.

I will take the help of the isspace function to find the whitespace character within the given input string. So let’s see the C program to trim leading and trailing white spaces from a string.

Examples:

Case 1:

Input String with leading and trailing whitespace:> "     aticle world .com      "



Output String:> "aticle world .com"

 

Case 2: 

Input String with trailing whitespace:> "aticle world .com      "


Output String:> "aticle world .com"

 

Case3:

Input String with leading whitespace:> "     aticle world .com"


Output String:> "aticle world .com"

 

 

C program to trim leading and trailing white spaces from a string:

Let’s some ways to trim leading and trailing whitespace characters from the given input string. You can use it according to your use.

 

If you can modify the input string:

The below function returns a pointer to a substring of the original string. Also If the given string was allocated dynamically, the programmer should use the original pointer to deallocate the allocated memory. They must not be used the return pointer for deallocating the memory.

Method 1:

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

char *trimwhitechar(char *str)
{
    if (str != NULL)
    {
        char *end;
        // Trim leading space
        while(isspace((unsigned char)*str))
        {
            ++str;
        }
        if(*str == 0)  // All spaces?
        {
            return str;
        }
        // Trim trailing space
        end = str + strlen(str) - 1;
        while(end > str && isspace((unsigned char)*end))
        {
            end--;
        }
        // Write new null terminator character
        end[1] = '\0';
    }
    return str;
}

int main()
{
    char str[] = "     aticle world .com      ";

    printf("\nString before trimming trailing white space: \n'%s'\n\n", str);

    char *p = trimwhitechar(str);

    printf("\n\nString after trimming trailing white spaces: \n'%s'\n\n", p);

    return 0;
}

Output:

isspace in C

 

Method 2:

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



void trimwhitechar(char* str)
{
    if ((str != NULL) && (*str != '\0'))
    {
        // First remove leading spaces
        const char* firstNonSpace = str;

        while(*firstNonSpace != '\0' && isspace((unsigned char)*firstNonSpace))
        {
            ++firstNonSpace;
        }

        unsigned int len = strlen(firstNonSpace);

        memmove(str, firstNonSpace, len);

        // Now remove trailing spaces
        char* endOfString = str + len;

        while(str < endOfString  && isspace((unsigned char)*endOfString))
        {
            --endOfString ;
        }

        *++endOfString = '\0';
    }

}


int main()
{
    char str[] = "     aticle world .com      ";

    printf("\nString before trimming trailing white space: \n'%s'\n\n", str);

    trimwhitechar(str);

    printf("\n\nString after trimming trailing white spaces: \n'%s'\n\n", str);

    return 0;
}

Output:

isspace in C

 

 

If you can not modify the input string:

This method is useful when you don’t want to modify the input string. In this method, we store the trimmed input string into the given output buffer, which must be large enough to store the result.

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


unsigned int trimwhitechar(char *outputBuffer, unsigned int givenStringLen, const char *str)
{

    unsigned int  outputBufferSize = 0;
    if((str != NULL)
            && (givenStringLen > 0))
    {
        const char *end;

        // Trim leading space
        while(isspace((unsigned char)*str))
            str++;

        if(*str == 0)  // All spaces?
        {
            *outputBuffer = 0;
            outputBufferSize = 1;
        }
        else
        {
            // Trim trailing space
            end = str + strlen(str) - 1;
            while(end > str && isspace((unsigned char)*end))
            {
                end--;
            }
            end++;
            // Set output size to minimum of trimmed string length and buffer size minus 1
            outputBufferSize = ((end - str) < (givenStringLen-1)) ? (end - str) : givenStringLen-1;

            // Copy trimmed string and add null terminator
            memcpy(outputBuffer, str, outputBufferSize);
            outputBuffer[outputBufferSize] = 0;
        }
    }

    return outputBufferSize;
}


int main()
{
    char str[] = "     aticle world .com      ";

    const unsigned int gievenStringSize = sizeof(str);

    char outputBuffer[gievenStringSize];

    printf("\nString before trimming trailing white char: \n'%s'\n\n", str);
    printf("\n\nString len before trimming trailing white char: \n%d\n\n", gievenStringSize);

    unsigned int lenSubString = trimwhitechar(outputBuffer,gievenStringSize,str);

    printf("\n\nString after trimming trailing white char: \n'%s'\n\n", outputBuffer);

    printf("\n\nString len after trimming trailing white char: \n%d\n\n", lenSubString);

    return 0;
}

Output:

isspace char in c

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *