Q:

C program to capitalize first character of each word in a string

belongs to collection: C String Programs

0

C program to capitalize first character of each word in a string

In this program, we will learn how to capitalize each word of input string using C program?

This program will read a string and print Capitalize string, Capitalize string is a string in which first character of each word is in Uppercase (Capital) and other alphabets (characters) are in Lowercase (Small).

For example:
If input string is "hello friends how are you?" then output (in Capitalize form) will be "Hello Friends How Are You?".

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program to capitalize first character of each word in a string in C

#include <stdio.h>
#define MAX 100

int main()
{
	char str[MAX]={0};	
	int i;
	
	//input string
	printf("Enter a string: ");
	scanf("%[^\n]s",str); //read string with spaces
	
	//capitalize first character of words
	for(i=0; str[i]!='\0'; i++)
	{
		//check first character is lowercase alphabet
		if(i==0)
		{
			if((str[i]>='a' && str[i]<='z'))
				str[i]=str[i]-32; //subtract 32 to make it capital
			continue; //continue to the loop
		}
		if(str[i]==' ')//check space
		{
			//if space is found, check next character
			++i;
			//check next character is lowercase alphabet
			if(str[i]>='a' && str[i]<='z')
			{
				str[i]=str[i]-32; //subtract 32 to make it capital
				continue; //continue to the loop
			}
		}
		else
		{
			//all other uppercase characters should be in lowercase
			if(str[i]>='A' && str[i]<='Z')
				str[i]=str[i]+32; //subtract 32 to make it small/lowercase
		}
	}
	
	printf("Capitalize string is: %s\n",str);
	
	return 0;
}

Output

First run:
Enter a string: HELLO FRIENDS HOW ARE YOU?
Capitalize string is: Hello Friends How Are You?

Second run:
Enter a string: hello friends how are you?
Capitalize string is: Hello Friends How Are You?

Third run:
Enter a string: 10 ways to learn programming.
Capitalize string is: 10 Ways To Learn Programming.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C String Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to find the frequency of a character in ... >>
<< C program to print indexes of a particular charact...