Example:
Input string: Lots of leading space.
Output: Lots of leading space.
Required knowledge
Basic C programming, Loop, String, FunctionLogic to remove leading white space
White space characters include Blank space(' '), Tab('\t'), New line('\n'). To remove leading white space characters from a string we need to perform two basic tasks:- Run a loop from starting of string till a white space is found.
- Shift all characters to its left from the last leading white space character found above.
Program to trim leading white space
/**
* C program to trim leading white space characters from a string
*/
#include <stdio.h>
#define MAX_SIZE 100 //Maximum size of the string
/* Function declaration */
void trimLeading(char * string);
int main()
{
char string[MAX_SIZE];
/* Reads string from user */
printf("Enter any string: ");
gets(string);
printf("String before trimming leading whitespace: %s\n", string);
trimLeading(string);
printf("String after trimming leading whitespace: %s\n", string);
return 0;
}
/**
* Remove leading whitespace characters from a string
*/
void trimLeading(char * string)
{
int lastSpaceIndex, i, j;
lastSpaceIndex = 0;
/* Finds the last index of whitespace character */
while(string[lastSpaceIndex] == ' ' || string[lastSpaceIndex] == '\t' || string[lastSpaceIndex] == '\n')
{
lastSpaceIndex++;
}
/* Shits all trailing characters to its left */
i = 0;
while(string[i + lastSpaceIndex] != '\0')
{
string[i] = string[i + lastSpaceIndex];
i++;
}
string[i] = '\0'; //Make sure that string is NULL terminated
}
Output
Enter any string: Lots of leading space!
String before trimming leading whitespace: Lots of leading space!
String after trimming leading whitespace: Lots of leading space!
String before trimming leading whitespace: Lots of leading space!
String after trimming leading whitespace: Lots of leading space!
Happy coding ;)
You may also like
- String programming exercises index.
- C program to trim trailing white space characters in a string.
- C program to trim leading and trailing white spaces characters.
- C program to remove extra blank spaces from a string.
- C program to toggle case of each character of a string.
- C program to count total number of words in a string.
- C program to find reverse of a string.
- C program to search all occurrences of a character in a string.
- C program to search all occurrences of a word in a string.
- C program to find highest frequency character in a string.
- C program to count frequency of each character in a string.
- C program to remove all occurrences of a character from a string.
- C program to remove all repeated characters from a string.