Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a formatting flag that converts to a lowercase String in Java?

There are two placeholders in Java that convert to a String:

  • %s -- converts to a String as-is
  • %S -- converts to an Uppercase String.

Thus, given:

String result = String.format(template, "Hi James!"); 
  • If template = "%s", the result will be "Hi James!"
  • If template = "%S", the result will be "HI JAMES!"

Question:

Generally, is there a way to convert an argument to a lowercase String using only Java's format conversion syntax? (In other words, without using toLowerCase().)
Specifically, is there any possible value for template such that the result will be "hi james!"?

like image 751
James Dunn Avatar asked Jul 24 '14 18:07

James Dunn


People also ask

How do you convert a string to lowercase in Java?

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

What does %s means in Java?

the %s is a 'format character', indicating "insert a string here". The extra parameters after the string in your two function calls are the values to fill into the format character placeholders: In the first example, %s will be replaced with the contents of the command variable.

Which is used to convert a string into lowercase?

The toLowerCase method converts a string to lowercase letters. The toLowerCase() method doesn't take in any parameters. Strings in JavaScript are immutable. The toLowerCase() method converts the string specified into a new one that consists of only lowercase letters and returns that value.

What is %d and %s in Java?

%d means number. %0nd means zero-padded number with a length. You build n by subtraction in your example. %s is a string. Your format string ends up being this: "%03d%s", 0, "Apple"


1 Answers

No, there is not. But, according to Java Docs:

Conversions denoted by an upper-case character (i.e. 'B', 'H', 'S', 'C', 'X', 'E', 'G', 'A', and 'T') are the same as those for the corresponding lower-case conversion characters except that the result is converted to upper case according to the rules of the prevailing Locale. The result is equivalent to the following invocation of String.toUpperCase()

In other words, the following

String result = String.format("%S", "Hi James!"); 

is equivalent to

String result = String.format("%s", "Hi James!").toUpperCase(); 

So, if you want to get a lower case string, you can just do:

String result = String.format("%s", "Hi James!").toLowerCase(); 

There won't be an optimization by doing the conversion using a flag.

like image 103
Christian Tapia Avatar answered Oct 15 '22 12:10

Christian Tapia