Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove preceding spaces and tabs from a given string in C language

What C function, if any, removes all preceding spaces and tabs from a string?

like image 377
goe Avatar asked Dec 05 '22 04:12

goe


2 Answers

In C a string is identified by a pointer, such as char *str, or possibly an array. Either way, we can declare our own pointer that will point to the start of the string:

char *c = str;

Then we can make our pointer move past any space-like characters:

while (isspace(*c))
    ++c;

That will move the pointer forwards until it is not pointing to a space, i.e. after any leading spaces or tabs. This leaves the original string unmodified - we've just changed the location our pointer c is pointing at.

You will need this include to get isspace:

#include <ctype.h>

Or if you are happy to define your own idea of what is a whitespace character, you can just write an expression:

while ((*c == ' ') || (*c == '\t'))
    ++c;
like image 143
Daniel Earwicker Avatar answered Apr 09 '23 05:04

Daniel Earwicker


A simpler function to trim white spaces

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

char * trim(char * buff);

int main()
{
    char buff[] = "    \r\n\t     abcde    \r\t\n     ";
    char* out = trim(buff);
    printf(">>>>%s<<<<\n",out);
}

char * trim(char * buff)
{
    //PRECEDING CHARACTERS
    int x = 0;
    while(1==1)
    {
        if((*buff == ' ') || (*buff == '\t') || (*buff == '\r') || (*buff == '\n'))
            { 
                x++;
                ++buff;
            }
        else
            break;
    }
    printf("PRECEDING spaces : %d\n",x);
    //TRAILING CHARACTERS
    int y = strlen(buff)-1;
    while(1==1)
    {
        if(buff[y] == ' ' || (buff[y] == '\t') || (buff[y] == '\r') || (buff[y] == '\n'))
            { 
                y--;
            }
        else
            break;
    }
    y = strlen(buff)-y;
    printf("TRAILING spaces : %d\n",y);
    buff[strlen(buff)-y+1]='\0';
    return buff;
}
like image 45
Howard J Avatar answered Apr 09 '23 05:04

Howard J