Home »
C programs »
C string programs
C program to eliminate/remove first character of each word from a string
In this program, we will learn how to eliminate/remove first character of each word in a string? Here, we will read a string and eliminate its first character of each word, then print new string (after elimination of first character of each words).
Logic to implement
- Eliminate first character of the string (first character of first word) by shifting other character to the left.
- Eliminate the first character of other word (by checking whether there is an index has space and index+1 (next to index where space found) non space and shift other characters to the left.
- Run this process until NULL not found in the parent loop.
Program to eliminate first character of each word of a string in C
#include <stdio.h>
#define MAX 100
int main()
{
char text[MAX]={0};
int loop,j;
printf("Please input string: ");
scanf("%[^\n]s",text); //read string with spaces
printf("Input string is...\n");
printf("%s\n",text);
for(loop=0; text[loop]!='\0'; loop++)
{
if(loop==0 || (text[loop]==' ' && text[loop+1]!=' '))
{
//shift next characters to the left
for(j=((loop==0)?loop:loop+1); text[j]!='\0'; j++)
text[j]=text[j+1];
}
}
printf("Value of \'text\' after eliminating first character of each word...\n");
printf("%s\n",text);
return 0;
}
Output
Please input string: Hello friends, how are you?
Input string is...
Hello friends, how are you?
Value of 'text' after eliminating first character of each word...
ello riends, ow re ou?
C String Programs »