Program to convert first character uppercase in a sentence

21 Apr, 2022
Write a Java program to convert the first character uppercase in a sentence and if apart from the first character if any other character is in Uppercase then convert into Lowercase?
Examples: 
Input : gEEKs
Output :Geeks

Input :GFG
Output :Gfg


Input : GeeksforGeeks
Output : Geeksforgeeks
Method 1: 
C++
Java
Python3
C#
Javascript
// C++ program to convert// first character uppercase// in a sentence#include<bits/stdc++.h>using namespace std;string convert(string str){  for (int i = 0;           i < str.length(); i++)  {    // If first character of a    // word is found    if (i == 0 && str[i] != ' ' ||        str[i] != ' ' && str[i - 1] == ' ')    {      // If it is in lower-case      if (str[i] >= 'a' && str[i] <= 'z')      {        // Convert into Upper-case        str[i] = (char)(str[i] - 'a' + 'A');      }    }     // If apart from first character    // Any one is in Upper-case    else if (str[i] >= 'A' &&             str[i] <= 'Z')       // Convert into Lower-Case      str[i] = (char)(str[i] + 'a' - 'A');  }   return str;} // Driver codeint main(){  string str = "gEEks fOr GeeKs";  cout << (convert(str));  return 0;} // This code is contributed by Chitranayal
// Java program to convert first character// uppercase in a sentenceclass GFG {     static String convert(String str)    {         // Create a char array of given String        char ch[] = str.toCharArray();        for (int i = 0; i < str.length(); i++) {             // If first character of a word is found            if (i == 0 && ch[i] != ' ' ||                ch[i] != ' ' && ch[i - 1] == ' ') {                 // If it is in lower-case                if (ch[i] >= 'a' && ch[i] <= 'z') {                     // Convert into Upper-case                    ch[i] = (char)(ch[i] - 'a' + 'A');                }            }             // If apart from first character            // Any one is in Upper-case            else if (ch[i] >= 'A' && ch[i] <= 'Z')                 // Convert into Lower-Case                ch[i] = (char)(ch[i] + 'a' - 'A');                   }         // Convert the char array to equivalent String        String st = new String(ch);        return st;    }     public static void main(String[] args)    {        String str = "gEEks fOr GeeKs";        System.out.println(convert(str));    }}
# Python3 program to convert first character# uppercase in a sentencedef convert(s):         # Create a char array of    # given string    ch = list(s)         for i in range(len(s)):          # If first character of a word is found        if (i == 0 and ch[i] != ' ' or                       ch[i] != ' ' and                       ch[i - 1] == ' '):              # If it is in lower-case            if (ch[i] >= 'a' and ch[i] <= 'z'):                  # Convert into Upper-case                ch[i] = chr(ord(ch[i]) - ord('a') +                            ord('A'))          # If apart from first character        # Any one is in Upper-case        elif (ch[i] >= 'A' and ch[i] <= 'Z'):              # Convert into Lower-Case            ch[i] = chr(ord(ch[i]) + ord('a') -                        ord('A'))         # Convert the char array    # to equivalent string    st = "".join(ch)             return st; # Driver code   if __name__=="__main__":         s = "gEEks fOr GeeKs"         print(convert(s));  # This code is contributed by rutvik_56
// C# program to convert first character// uppercase in a sentenceusing System; class GFG {         static String convert(String str)    {         // Create a char array of        // given String        char []ch = str.ToCharArray();                 for (int i = 0; i < str.Length; i++)        {             // If first character of a            // word is found            if (i == 0 && ch[i] != ' ' ||                ch[i] != ' ' && ch[i - 1] == ' ')            {                 // If it is in lower-case                if (ch[i] >= 'a' && ch[i] <= 'z')                {                     // Convert into Upper-case                    ch[i] = (char)(ch[i] - 'a' + 'A');                }            }             // If apart from first character            // Any one is in Upper-case            else if (ch[i] >= 'A' && ch[i] <= 'Z')                 // Convert into Lower-Case                ch[i] = (char)(ch[i] + 'a' - 'A');                }         // Convert the char array to        // equivalent String        String st = new String(ch);                 return st;    }     // Driver code    public static void Main()    {        String str = "gEEks fOr GeeKs";        Console.Write(convert(str));    }} // This code is contributed by Nitin Mittal.
<script>// Javascript program to convert first character// uppercase in a sentence         function convert(str)    {        // Create a char array of given String        let ch = str.split("");        for (let i = 0; i < str.length; i++) {              // If first character of a word is found            if (i == 0 && ch[i] != ' ' ||                ch[i] != ' ' && ch[i - 1] == ' ') {                  // If it is in lower-case                if (ch[i] >= 'a' && ch[i] <= 'z') {                      // Convert into Upper-case                    ch[i] = String.fromCharCode(ch[i].charCodeAt(0) - 'a'.charCodeAt(0) + 'A'.charCodeAt(0));                }            }              // If apart from first character            // Any one is in Upper-case            else if (ch[i] >= 'A' && ch[i] <= 'Z')                  // Convert into Lower-Case                ch[i] = String.fromCharCode(ch[i].charCodeAt(0) + 'a'.charCodeAt(0) - 'A'.charCodeAt(0));                  }          // Convert the char array to equivalent String        let st = (ch).join("");        return st;    }              let str = "gEEks fOr GeeKs";    document.write(convert(str));         // This code is contributed by avanitrachhadiya2155</script>
Output: 
Geeks For Geeks
Method 2: Using Java Inbuilt methods To capitalize each word, call the toLowerCase() method to put the string in lowercase format. Iterate the string, if any space if found in the previous iteration and the current element is not space then call the toUpperCase() method to put the first letter of the word in uppercase format and append the string in the buffer. 
Below is the implementation:
Java
// Java Program to capitalize each word in a stringpublic class GFG {     // Method to convert the string    static String capitailizeWord(String str) {        StringBuffer s = new StringBuffer();         // Declare a character of space        // To identify that the next character is the starting        // of a new word        char ch = ' ';        for (int i = 0; i < str.length(); i++) {                         // If previous character is space and current            // character is not space then it shows that            // current letter is the starting of the word            if (ch == ' ' && str.charAt(i) != ' ')                s.append(Character.toUpperCase(str.charAt(i)));            else                s.append(str.charAt(i));            ch = str.charAt(i);        }         // Return the string with trimming        return s.toString().trim();    }     // Driver Code    public static void main(String args[]) {         // Declare the string        String s1 = "gEEks fOr GeeKs";         // Convert that string into lowercase        s1 = s1.toLowerCase();         // Call the method to capitalize each word        System.out.println(capitailizeWord(s1));    }}
Method 3 : Using Python3 
Approach : We can create a list of all the words in a sentence (say string_array). After creating string_array, if we directly work upon that list and try to change the lowercase starting characters of words, we will get an error ” ‘str’ object does not support item assignment“. To avoid this we can create a list of ASCII values (say ascii_array) of characters corresponding to the characters in string_array.
We can easily work upon ascii_array and convert the starting lowercase characters of words to uppercase by simply subtracting 32 from their ASCII value. After changing the values in ascii_array, we convert each ASCII value in ascii_array to their corresponding characters by using chr() function. chr() function returns the character corresponding to the ASCII value passed in parameters. This way we will obtain a list of capitalized strings.
Below is the implementation of the above approach 
Python3
# Python program to capitalize the# first character of each word in a sentence # Function definitiondef solve (st):    ascii_array = []         # creating a list of ascii values    # of all the characters in the sentence    for i in range (0, len (st)):        ascii_array.append (ord (st[i]))         # check if the first character of    # each word is a lowercase character.    # To convert a lowercase character to an    # uppercase character, we subtract 32 from    # the ASCII value of lowercase character.    if ascii_array[0] >= 97 and ascii_array[0] <= 122 :        ascii_array[0] = ascii_array[0] - 32         # create an empty list which will store    # the characters corresponding to the    # ascii values in ascii_array    newlist = []    newlist.append (chr (ascii_array[0]))    for i in range (1, len (ascii_array)):                 # 32 is the ascii value for 'space' or ' '.        # so we use this condition to check for        # the next word in the sentence        # as in a sentence we have space separated words        if ascii_array[i] == 32:            if ascii_array[i + 1] >= 97 and ascii_array[i+1] <= 122:                ascii_array[i + 1] = ascii_array[i+1] - 32        newlist.append (chr (ascii_array[i]))             # in the end, we return a string after    # joining the values obtained in newlist    return (''.join (newlist)) # Driver Codestring = 'geeks for geeks'result = solve (string)print (result)# This code is contributed by Kishan Mishra
Geeks For Geeks
 
nitin mittal
bilal-hungund
mishrakishan1
rutvik_56
ukasp
avanitrachhadiya2155
simmytarika5
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream In Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class