Trimming leading white spaces from a string means removing any unnecessary spaces before the first non-space character in the string. In this article, we will learn how to trim leading white spaces using the C program.
The most straightforward method to trim leading white spaces from the string is by using a two-pointer approach. Let’s take a look at an example:
#include <stdio.h>
void trim(char *s) {
// Two pointers initially at the beginning
int i = 0, j = 0;
// Skip leading spaces
while (s[i] == ' ') i++;
// Shift the characters of string to remove
// leading spaces
while (s[j++] = s[i++]);
}
int main() {
char s[] = " Hello, Geeks!";
// Remove leading whitespaces from s
trim(s);
printf("'%s'\n", s);
return 0;
}
Output
'Hello, Geeks!'
Explanation: The above program uses two pointers: i finds the first non-space character, while j copies subsequent characters to the beginning of the string, effectively removing the leading spaces. Finally, it null-terminates the trimmed string.
There are also some other ways to remove the leading whitespace from a string in C. Some of them are given below:
Using Pointer Arithmetic
Instead of using array indexing, we can use pointer arithmetic to traverse the string. We move the pointer to the first non-space character and then shift the string to remove the leading spaces.
#include <stdio.h>
#include <string.h>
void trim(char *s) {
// Pointer to the beginning of the trimmed string
char *ptr = s;
// Skip leading spaces
while (*s == ' ') s++;
// Shift remaining characters to the beginning
while (*ptr++ = *s++);
}
int main() {
char s[] = " Hello, Geeks!";
// Remove leading whitespaces from s
trim(s);
printf("%s\n", s);
return 0;
}
Output
'Hello, Geeks!'