Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to uppercase without using the toUpperCase method?

Tags:

java

string

I'm a beginner at java and can't get this code to work. What I have to do is convert any inputted string to uppercase without using the toUpperCase string method. This is what I have:

public String toUpperCase(String str)
{
    for(int i = 0; i < str.length(); i++)
    {
        char a = str.charAt(i);
        a = Character.toUpperCase(a);
        str += Character.toString(a);
    }
return str;
}
like image 958
Nicole Havin Avatar asked Dec 14 '16 23:12

Nicole Havin


People also ask

How do you convert a string to uppercase?

Java String toUpperCase() Method The toUpperCase() method converts a string to upper case letters. Note: The toLowerCase() method converts a string to lower case letters.

How do I convert a lowercase string to uppercase?

Program to convert the uppercase string into lowercase using the strlwr() function. Strlwr() function: The strlwr() function is a predefined function of the string library used to convert the uppercase string into the lowercase by passing the given string as an argument to return the lowercase string.

What is the difference between toUpperCase () and toLowerCase ()?

The toLowerCase operator takes a string and converts it to all lower case letters. The toUpperCase operator takes a string and converts it to all uppercase letters.


1 Answers

You are using str as input, and output (so your String has infinite length, as you keep adding characters). And you can use static, because you aren't using instance state. And, you might use a for-each loop. Finally, add another String, or better a StringBuilder like

public static String toUpperCase(String str) {
    StringBuilder sb = new StringBuilder();
    for (char ch : str.toCharArray()) {
        sb.append(Character.toUpperCase(ch));
    }
    return sb.toString();
}
like image 106
Elliott Frisch Avatar answered Nov 14 '22 20:11

Elliott Frisch