C program to trim leading white spaces from String

Given string str, the task is to write C program to remove leading space from the given string.

Examples :

Input: str = ”       geeksforgeeks”
Output: geeksforgeeks

Input: str = “gfg”
Output: gfg


Approach: The idea is to count the leading spaces in the given string and then from that count index copy the characters from that index to the front of the string. Below are the steps:

  1. Initialize count = 0 to count the number of leading spaces.
  2. Iterate through given string and find the index(say idx) at which the leading space character ends.
  3. Iterate through all the characters from that index idx and copy each character from this index to the end to the front index.
  4. Finally, put ‘\0’ at the last index of the new string to terminate the string.

Below is the implementation of the above approach:






// C program for the above approach
#include <stdio.h>
// Function to remove leading
// spaces from a given string
char* removeLeadingSpaces(char* str)
    static char str1[99];
    int count = 0, j, k;
    // Iterate String until last
    // leading space character
    while (str[count] == ' ') {
    // Putting string into another
    // string variable after
    // removing leading white spaces
    for (j = count, k = 0;
         str[j] != '\0'; j++, k++) {
        str1[k] = str[j];
    str1[k] = '\0';
    return str1;
// Driver Code
int main()
    // Given string
    char str[] = "         geeksforgeeks";
    char* ptr;
    // Function call
    ptr = removeLeadingSpaces(str);
    // Print string without leading space
    printf("%s", ptr);
    return 0;




Time Complexity: O(N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.