Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

C program to trim leading white spaces from String

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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:


// GeeksforGeeks
// C program to trim leading whitespaces
#include <stdio.h>
void removeLeading(char *str, char *str1)
    int idx = 0, j, k = 0;
    // Iterate String until last
    // leading space character
    while (str[idx] == ' ' || str[idx] == '\t' || str[idx] == '\n')
    // Run a for loop from index until the original
    // string ends and copy the content of str to str1
    for (j = idx; str[j] != '\0'; j++)
        str1[k] = str[j];
    // Insert a string terminating character
    // at the end of new string
    str1[k] = '\0';
    // Print the string with no whitespaces
    printf("%s", str1);
// Driver Code
int main()
    // Given string
    char str[] = "          geeksforgeeks";
    char str1[100];
    // Function call
    removeLeading(str, str1);
    return 0;
// Code contributed by vpsop



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

My Personal Notes arrow_drop_up
Last Updated : 11 Aug, 2022
Like Article
Save Article
Similar Reads
Related Tutorials