Program to convert first character uppercase in a sentence

Write a Java program to convert 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:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to convert first character
// uppercase in a sentence
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;
    }
  
    public static void main(String[] args)
    {
        String str = "gEEks fOr GeeKs";
        System.out.println(convert(str));
    }
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to convert first character
// uppercase in a sentence
using 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.

chevron_right


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 previous iteration and current element is not space then call the toUpperCase() method to put the first letter of word in uppercase format and append the string in buffer.
Below is the implementation:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to capitalize each word in a string
public 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));
    }
}

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to capitalize the
# first character of each word in a sentence
  
# Function definition
def 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 Code
string = 'geeks for geeks'
result = solve (string)
print (result)
# This code is contributed by Kishan Mishra

chevron_right


Output:

Geeks For Geeks

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


5


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.