C program to remove the first character of each word of a string

C program to remove first character of each word of a string :

In this tutorial , we will learn how to remove the first character of each word from a string in C. We are going to use two arrays in this program. The first array will hold the user input and the second array will hold the modified final string. Let’s take a look into the algorithm first :

Algorithm to remove first character of each word from a string :

1. Store the user input string in an array.
2. Since we are going to remove the first letter of the string anyways,so start scanning from the second letter character by character.
3. Put it in the final array.
4. If the current scanning character is blank and the next character is not blank, meaning it is the start of a word, increment the current value of the index.Since we don’t want to store the first character of that word in the final array.
5. Finally,print the array stored in the final variable.

C program :

#include< stdio.h >
#define MAX_SIZE 100

int main()
{
	//1
	char input_string[MAX_SIZE];
	char final_string[MAX_SIZE];

	//2
	int i,j = 0;

	//3
	printf("Enter your string : ");
	scanf("%[^\n]s",input_string);

	//4
	printf("\nyou have entered %s\n",input_string); 


	//5
	for(i = 1; input_string[i] != '\0'; i++){

		//6
		final_string[j] = input_string[i];
		
		//7
		if(input_string[i] == ' ' && input_string[i+1] != ' '){
			i++;
		}
		//8
		j++;
	}

	//9
	printf("\nFinal string : %s \n",final_string);

    return 0;
}

Explanation :

The commented numbers in the above program denote the step-number below :

1. Create two char array variable to store the user input string and final output string.
2. Create two integer variables i and j.i will indicate the current scanning position of the user input array and j will indicate the current position of the final array. We will scan character by character from the input_string array and put it in the final_string array.
3. Ask the user to enter a string and store it in input_string variable.
4. Print out the string user has entered.
5. Run one for loop and scan each character of the string one by one. We are starting from i = 1 i.e. from the second character of the string.
6. Put each character of the string in final_string variable.
7. Check if the current character is blank and next character is not null. If yes, increment the value of i.
8. Increment the value of j.
9. Finally print the value of the final_string.

Sample Output :

Enter your string : welcome to codevscolor blog

you have entered welcome to codevscolor blog

Final string : elcome o odevscolor log


Enter your string : hello world

you have entered hello world

Final string : ello orld

Enter your string : one more string with lots of words

you have entered one more string with lots of words

Final string : ne ore tring ith ots f ords

Leave a Reply