'Is there a way to remove all leading and trailing whitespaces of a string in C without the use of external librarys? [closed]

I have been recently trying to make an OS using the C language. The OS shell needs to get the string "ADD" from the string " ADD ". I need to get rid of the whitespaces from the start and end to get the command on its own. I tried other methods which use standard libraries, and so I can't use. Can anyone help me trim the whitespaces from the start and end of a string without std libraries? (compiler is GCC)

something like:

char* text = "     ADD     ";
char* newtext = trim(text);


Solution 1:[1]

Yes, there is.

Since you are trying to write an OS, or more specifically a binary capable of booting and displaying a shell, and you stated you can't use the standard C library, I will assume you also don't have a way to dynamically allocate memory (unless you already wrote your own allocator).

So, you need to modify the string in place.

For that, you need to do the following:

  1. Calculate the number of spaces at the beginning of string.
    This is a simple for loop.

  2. Calculate the number of space at the end of string.
    This is also a simple for loop, but running backwards.

  3. Calculate the length of clean string by subtracting the amount of space from string length.

  4. Move the clean string to the beginning of the array an put a null char terminator at clean string length.
    This is also a simple for loop.

Putting it all together, here is a function for you:

void strip_in_place(char *string, int length) {
    int prefix_spaces = 0;
    int postfix_spaces = 0;

    int index = 0;

    //find spaces at the beginning:
    while(index < length && string[index] == ' ') {
        prefix_spaces++;
        index++;
    }

    index = length - 1;

    //find spaces at the end:
    while(index > 0 && string[index] == ' ') {
        postfix_spaces++;
        index--;
    }

    int clean_length = length - (prefix_spaces + postfix_spaces);

    //move the string to erase spaces at the beginning
    for (index = 0; index < clean_length; index++) {
        string[index] = string[index + prefix_spaces];
    }

    //terminate to delete spaces at the end
    string[clean_length] = '\0';
}

Note, I did not compile and test this code, as your question may get closed by the time I do so.

Also, if you understand the general idea, you should be able to fix any bugs in it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lev M.