Lowercase to uppercase conversion without using any library function in Java

Java lowercase to uppercase conversion: Here, we are going to learn how to convert lowercase string to uppercase without using any library function in Java?
Submitted by IncludeHelp, on July 12, 2019

Given a string and we have to convert it from lowercase to uppercase.

Examples:

    Input:
    IncludeHelp.com
    Output:
    INCLUDEHELP.COM

    Input:
    123abcd@9081
    Output:
    123ABCD@9081

Lowercase to uppercase conversion

To convert a lowercase alphabet to uppercase alphabet – we can subtract 32 from lowercase alphabet's ASCII code to make it an uppercase alphabet (because the difference between a lowercase alphabet ASCII and an uppercase alphabet ASCII is 32).

In the below code, we created a user-defined function LowerToUpper() that will accept a string and returns string having uppercase characters. To convert lowercase alphabets of the string to uppercase alphabets, we are extracting characters one by one from the string using String.charAt() function and checking whether the character is a lowercase alphabet, if it is a lowercase alphabet, we are subtracting 32 to make it uppercase, else no change. Thus, only lowercase alphabets will be converted to uppercase alphabets, the rest of the characters like uppercase alphabets, digits and special characters will remain the same.

Java code for lowercase to uppercase conversion

// Lowercase to uppercase conversion without using 
// any library function in Java

public class Main {
    static String LowerToUpper(String s) {
        String result = "";
        char ch = ' ';
        for (int i = 0; i < s.length(); i++) {
            
            //check valid alphabet and it is in lowercase
            if (s.charAt(i) >= 'a' && s.charAt(i) <= 'z') {
                ch = (char)(s.charAt(i) - 32);
            }
            //else keep the same alphabet or any character
            else {
                ch = (char)(s.charAt(i));
            }
            
            result += ch; // concatenation, append c to result
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(LowerToUpper("IncludeHelp.com"));
        System.out.println(LowerToUpper("www.example.com"));
        System.out.println(LowerToUpper("123abcd@9081"));
        System.out.println(LowerToUpper("OKAY@123"));       
    }
}

Output

INCLUDEHELP.COM
WWW.EXAMPLE.COM
123ABCD@9081
OKAY@123

Java String Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.