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:
- Initialize count = 0 to count the number of leading spaces.
- Iterate through given string and find the index(say idx) at which the leading space character ends.
- Iterate through all the characters from that index idx and copy each character from this index to the end to the front index.
- Finally, put ‘\0’ at the last index of the new string to terminate the string.
Below is the implementation of the above approach:
C
#include <stdio.h>
void removeLeading( char *str, char *str1)
{
int idx = 0, j, k = 0;
while (str[idx] == ' ' || str[idx] == '\t' || str[idx] == '\n' )
{
idx++;
}
for (j = idx; str[j] != '\0' ; j++)
{
str1[k] = str[j];
k++;
}
str1[k] = '\0' ;
printf ( "%s" , str1);
}
int main()
{
char str[] = " geeksforgeeks" ;
char str1[100];
removeLeading(str, str1);
return 0;
}
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Last Updated :
11 Aug, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...