Write a C program to trim leading white space characters from a given string using loop. How to remove leading white space characters from a given string using loop in C programming. Logic to remove leading/starting blank spaces from a given string in C programming.
Example
Input
Input string: Lots of leading space.
Output
String after removing leading white spaces: Lots of leading space.
Required knowledge
Basic C programming, Loop, String, Function
Must know – Program to remove elements from array
Logic to remove leading white space
White space characters include blank space ‘ ‘, tab ‘\t’, new line ‘n’.
Below is the step by step descriptive logic to remove leading white space characters from string.
- Input string from user, store it in some variable say str.
- Declare a variable to store last index of leading white space character, say index = -1. Initially I have assumed that there are no leading white space characters. Hence, index is initialized to -1.
- Run a loop from start till leading white space characters are found in str. Store the last index of leading white space character in index.
- Check if index == -1, then the given string contains no leading white space characters.
- If index != -1, then shift characters to left from the current index position.
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 string size
/* Function declaration */
void trimLeading(char * str);
int main()
{
char str[MAX_SIZE];
/* Input string from user */
printf("Enter any string: ");
gets(str);
printf("\nString before trimming leading whitespace: \n%s", str);
trimLeading(str);
printf("\n\nString after trimming leading whitespace: \n%s", str);
return 0;
}
/**
* Remove leading whitespace characters from string
*/
void trimLeading(char * str)
{
int index, i, j;
index = 0;
/* Find last index of whitespace character */
while(str[index] == ' ' || str[index] == '\t' || str[index] == '\n')
{
index++;
}
if(index != 0)
{
/* Shit all trailing characters to its left */
i = 0;
while(str[i + index] != '\0')
{
str[i] = str[i + index];
i++;
}
str[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!
Happy coding 😉
Recommended posts
- String programming exercises index.
- C program to trim trailing whitespace characters in given string.
- C program to trim both leading and trailing whitespace characters in string.
- C program to remove extra blanks from a given string.
- C program to remove all repeated characters from string.
- C program to replace all occurrences of a character in given string.
- C program to reverse order of string.