Converting to Upper and Lower Case in Java

change the string into uppercase and lowercase in java

This will work for you

 String s = "I Love java Programs";
String[] strArr = s.split(" ");
for (int i = 0; i < strArr.length; i++) {
String str = strArr[i];
int min = Math.min(i + 1, str.length());
String finalStr = str.substring(0, min) + (str.substring(min, str.length())).toUpperCase();
System.out.print(finalStr + " ");
}

The output will be:- "I LoVE javA ProgRAMS "

strArr[] will store the values like this: [I, Love, java, Programs]

Iterate over the array and use the index to determine how many characters we need to ignore (i.e. for 1st word 1 character, for 2nd word 2 characters and so on), for that I am using str.subString(0, i+1)
And we will use String#toUpperCase() to convert the remaining characters to upper case.

How do I convert strings between uppercase and lowercase in Java?

String#toLowerCase and String#toUpperCase are the methods you need.

text conversion into random upper and lowercase in java

String str = "hello good morning";
char[] letters = str.toCharArray();
StringBuilder sb = new StringBuilder(letters.length);
for (int i = 0; i < letters.length; i++) {
if (i % 2 == 0) {
sb.append(Character.toLowerCase(letters[i]));
else {
sb.append(Character.toUpperCase(letters[i]));
}
}

First letter is lower-case, second letter is upper-case, third letter is lower-case, etc. As requested, alternating upper and lower case. If you want to start with upper-case, rather than lower-case as in the above code, simply change the condition in the if statement to...

if (i % 2 == 1) {

Convert java char inside string to lowerCase/upperCase

You are adding characters to the original string. Also, this means that your for loop will never get to the end of the iteration of the for loop, because originalString.length() changes each loop also. It's an infinite loop.

Instead, create a StringBuilder that stores the converted characters as you're iterating over the original string. The convert it to a String and return it at the end.

StringBuilder buf = new StringBuilder(originalString.length());
for (int i = 0; i < originalString.length(); i++) {
char c = originalString.charAt(i);

if (Character.isUpperCase(c)) {
buf.append(Character.toLowerCase(c));

}
else if (Character.isLowerCase(c)) {
buf.append(Character.toUpperCase(c));

}
// Account for case: neither upper nor lower
else {
buf.append(c);
}

}
return buf.toString();

Fastest way of converting uppercase to lowercase and lowercase to uppercase in Java

As promised, here are two JMH benchmarks; one comparing Character#toUpperCase to your bitwise method, and the other comparing Character#toLowerCase to your other bitwise method. Note that only characters within the English alphabet were tested.

First Benchmark (to uppercase):

@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Fork(3)
public class Test {

@Param({"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"})
public char c;

@Benchmark
public char toUpperCaseNormal() {
return Character.toUpperCase(c);
}

@Benchmark
public char toUpperCaseBitwise() {
return (char) (c & 65503);
}
}

Output:

Benchmark                (c)  Mode  Cnt  Score   Error  Units
Test.toUpperCaseNormal a avgt 30 2.447 ± 0.028 ns/op
Test.toUpperCaseNormal b avgt 30 2.438 ± 0.035 ns/op
Test.toUpperCaseNormal c avgt 30 2.506 ± 0.083 ns/op
Test.toUpperCaseNormal d avgt 30 2.411 ± 0.010 ns/op
Test.toUpperCaseNormal e avgt 30 2.417 ± 0.010 ns/op
Test.toUpperCaseNormal f avgt 30 2.412 ± 0.005 ns/op
Test.toUpperCaseNormal g avgt 30 2.410 ± 0.004 ns/op

Test.toUpperCaseBitwise a avgt 30 1.758 ± 0.007 ns/op
Test.toUpperCaseBitwise b avgt 30 1.789 ± 0.032 ns/op
Test.toUpperCaseBitwise c avgt 30 1.763 ± 0.005 ns/op
Test.toUpperCaseBitwise d avgt 30 1.763 ± 0.012 ns/op
Test.toUpperCaseBitwise e avgt 30 1.757 ± 0.003 ns/op
Test.toUpperCaseBitwise f avgt 30 1.755 ± 0.003 ns/op
Test.toUpperCaseBitwise g avgt 30 1.759 ± 0.003 ns/op

Second Benchmark (to lowercase):

@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 5, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(iterations = 10, time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Fork(3)
public class Test {

@Param({"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"})
public char c;

@Benchmark
public char toLowerCaseNormal() {
return Character.toUpperCase(c);
}

@Benchmark
public char toLowerCaseBitwise() {
return (char) (c | 32);
}
}

Output:

Benchmark                (c)  Mode  Cnt  Score   Error  Units
Test.toLowerCaseNormal A avgt 30 2.084 ± 0.007 ns/op
Test.toLowerCaseNormal B avgt 30 2.079 ± 0.006 ns/op
Test.toLowerCaseNormal C avgt 30 2.081 ± 0.005 ns/op
Test.toLowerCaseNormal D avgt 30 2.083 ± 0.010 ns/op
Test.toLowerCaseNormal E avgt 30 2.080 ± 0.005 ns/op
Test.toLowerCaseNormal F avgt 30 2.091 ± 0.020 ns/op
Test.toLowerCaseNormal G avgt 30 2.116 ± 0.061 ns/op

Test.toLowerCaseBitwise A avgt 30 1.708 ± 0.006 ns/op
Test.toLowerCaseBitwise B avgt 30 1.705 ± 0.018 ns/op
Test.toLowerCaseBitwise C avgt 30 1.721 ± 0.022 ns/op
Test.toLowerCaseBitwise D avgt 30 1.718 ± 0.010 ns/op
Test.toLowerCaseBitwise E avgt 30 1.706 ± 0.009 ns/op
Test.toLowerCaseBitwise F avgt 30 1.704 ± 0.004 ns/op
Test.toLowerCaseBitwise G avgt 30 1.711 ± 0.007 ns/op

I've only included a few different letters (even though all were tested), as they are all share similar outputs.

It's clear that your bitwise methods are faster, mainly due to Character#toUpperCase and Character#toLowerCase performing logical checks (as I had mentioned earlier today in my comment).

Issues with Converting Upper to Lower Case in Java (Could it be memory location issues?)

It's because of a trailing whitespace at the end.
After completing the inner for loop for Terence, it is adding an additional whitespace at the end. So your string is "Alex Terence " not "Alex Terence"
After the outer for loop trim the string like this to remove the trailing whitespace.

searchName = searchName.trim()

An alternative approach to prevent this from happening in the first place would be to use the static join() method of the String class.

public static void main(String args[])
{
String searchName = "aLeX teReNce";

String[] str = searchName.split(" ");

searchName = "";

for(int i = 0; i < str.length; i++)
{
searchName += toUpper(str[i].charAt(0));

for(int j = 1; j < str[i].length(); j++)
{
searchName += toLower(str[i].charAt(j));
}

str[i] = searchName;
}

searchName = String.join(" ", str);
System.out.println("After Rearrange: " + searchName);
System.out.println();

if(searchName.equals("Alex Terence"))
{
System.out.println("True");
}

}

EDIT:
You're getting the strange symbol because there's an error in both your toUpper() and toLower() methods.
It won't give you the right output if you have an a/A or z/Z in your name because you have stated the conditon as upper<A and upper>Zwhich doesn't include A/a and Z/z. Change it to:

upper >= 'A' && upper <= 'Z'
lower >= 'a' && lower <= 'z'

What's happening is the a in teRaNce is passed to the toLower() method. Since it is already lowercase it shouldn't be converted but a and z were not included in your condition and hence it qualifies to be converted which adds 32 to a which gives you the character corresponding to 129.

Converting to upper and lower case in Java

Try this on for size:

String properCase (String inputVal) {
// Empty strings should be returned as-is.

if (inputVal.length() == 0) return "";

// Strings with only one character uppercased.

if (inputVal.length() == 1) return inputVal.toUpperCase();

// Otherwise uppercase first letter, lowercase the rest.

return inputVal.substring(0,1).toUpperCase()
+ inputVal.substring(1).toLowerCase();
}

It basically handles special cases of empty and one-character string first and correctly cases a two-plus-character string otherwise. And, as pointed out in a comment, the one-character special case isn't needed for functionality but I still prefer to be explicit, especially if it results in fewer useless calls, such as substring to get an empty string, lower-casing it, then appending it as well.

How to get upper case instead of lower case in a string without method toUppercase. P.S below

You can do it as follows:

public class Task1 {
public static void main(String[] args) {
System.out.println(lowerCase("HELLO"));
}

private static String lowerCase(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 65 && ch <= 90)
sb.append((char)(ch+32));
else
sb.append((char)ch);
}
return sb.toString();
}
}

Output:

hello

Please check https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html for reference.

UPDATE: Adding a method to convert a String to upper case as well

public class Task1 {
public static void main(String[] args) {
System.out.println(lowerCase("HELLO"));
System.out.println(upperCase("hello"));
}

private static String lowerCase(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 65 && ch <= 90) //ASCII value of 'A'is 65 and that of 'Z' is 90
sb.append((char)(ch+32));
else
sb.append((char)ch);
}
return sb.toString();
}
private static String upperCase(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch >= 97 && ch <= 122) //ASCII value of 'a'is 97 and that of 'z' is 122
sb.append((char)(ch-32));
else
sb.append((char)ch);
}
return sb.toString();
}
}

Output:

hello
HELLO


Related Topics



Leave a reply



Submit