Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C Program to convert first character uppercase in a sentence
Given a string with mixed case letters, the task is to convert the first character of each word to uppercase and the rest to lowercase. This creates a proper title case format where each word begins with a capital letter.
For example, given the string "hElLo world", we need to convert the first character 'h' to uppercase 'H' and make all other characters lowercase except for the first character after spaces, which should also be uppercase.
Syntax
void convertToTitleCase(char str[], int n);
Example Input and Output
Input: str[] = {"heLlO wORLD"}
Output: Hello World
Input: str[] = {"sUNIDHi bAnSAL"}
Output: Sunidhi Bansal
Approach
The approach uses ASCII values to convert characters −
- ASCII values for uppercase letters A-Z range from 65-90
- ASCII values for lowercase letters a-z range from 97-122
- The difference between lowercase and uppercase is 32 ('a' - 'A' = 32)
- Convert first character and characters after spaces to uppercase
- Convert all other alphabetic characters to lowercase
Example: Converting to Title Case
#include <stdio.h>
void convertToTitleCase(char str[], int n) {
int i;
for (i = 0; i < n; i++) {
if (i == 0 && str[i] != ' ' || str[i] != ' ' && str[i-1] == ' ') {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32;
}
} else if (str[i] >= 'A' && str[i] <= 'Z') {
str[i] = str[i] + 32;
}
}
}
int main() {
char str[] = "sUNIDHi bAnSAL";
int n = sizeof(str) - 1;
printf("Original: %s
", str);
convertToTitleCase(str, n);
printf("Title Case: %s
", str);
return 0;
}
Original: sUNIDHi bAnSAL Title Case: Sunidhi Bansal
How It Works
- First Character Check: If character is at position 0 or follows a space, convert to uppercase
- ASCII Conversion: Subtract 32 to convert lowercase to uppercase, add 32 for the reverse
-
String Length: Use
sizeof(str) - 1to exclude the null terminator
Conclusion
This program efficiently converts any mixed-case string to title case using ASCII arithmetic. It handles multiple words separated by spaces and ensures proper capitalization for readability.
Advertisements
