问题
I am using Java to get a String
input from the user. I am trying to make the first letter of this input capitalized.
I tried this:
String name;
BufferedReader br = new InputStreamReader(System.in);
String s1 = name.charAt(0).toUppercase());
System.out.println(s1 + name.substring(1));
which led to these compiler errors:
Type mismatch: cannot convert from InputStreamReader to BufferedReader
Cannot invoke toUppercase() on the primitive type char
回答1:
String str = "java";
String cap = str.substring(0, 1).toUpperCase() + str.substring(1);
// cap = "Java"
With your example:
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Actually use the Reader
String name = br.readLine();
// Don't mistake String object with a Character object
String s1 = name.substring(0, 1).toUpperCase();
String nameCapitalized = s1 + name.substring(1);
System.out.println(nameCapitalized);
}
回答2:
StringUtils.capitalize(..) from commons-lang
回答3:
The shorter/faster version code to capitalize the first letter of a String is:
String name = "stackoverflow";
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
the value of name
is "Stackoverflow"
回答4:
Use Apache's common library. Free your brain from these stuffs and avoid Null Pointer & Index Out Of Bound Exceptions
Step 1:
Import apache's common lang library by putting this in build.gradle
dependencies
compile 'org.apache.commons:commons-lang3:3.6'
Step 2:
If you are sure that your string is all lower case, or all you need is to initialize the first letter, directly call
StringUtils.capitalize(yourString);
If you want to make sure that only the first letter is capitalized, like doing this for an enum
, call toLowerCase()
first and keep in mind that it will throw NullPointerException
if the input string is null.
StringUtils.capitalize(YourEnum.STUFF.name().toLowerCase());
StringUtils.capitalize(yourString.toLowerCase());
Here are more samples provided by apache. it's exception free
StringUtils.capitalize(null) = null
StringUtils.capitalize("") = ""
StringUtils.capitalize("cat") = "Cat"
StringUtils.capitalize("cAt") = "CAt"
StringUtils.capitalize("'cat'") = "'cat'"
Note:
WordUtils
is also included in this library, but is deprecated. Please do not use that.
回答5:
What you want to do is probably this:
s1 = name.substring(0, 1).toUpperCase() + name.substring(1);
(converts first char to uppercase and adds the remainder of the original string)
Also, you create an input stream reader, but never read any line. Thus name
will always be null
.
This should work:
BufferedReader br = new InputstreamReader(System.in);
String name = br.readLine();
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1);
回答6:
Java:
simply a helper method for capitalizing every string.
public static String capitalize(String str)
{
if(str == null) return str;
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
After that simply call str = capitalize(str)
Kotlin:
str.capitalize()
回答7:
WordUtils.capitalize(java.lang.String) from Apache Commons.
回答8:
Below solution will work.
String A = "stackOverflow";
String ACaps = A.toUpperCase().charAt(0)+A.substring(1,A.length());
//Will print StackOverflow
You can't use toUpperCase() on primitive char , but you can make entire String to Uppercase first then take the first char, then to append to the substring as shown above.
回答9:
Use WordUtils.capitalize(str).
回答10:
Set the string to lower case, then set the first Letter to upper like this:
userName = userName.toLowerCase();
then to capitalise the first letter:
userName = userName.substring(0, 1).toUpperCase() + userName.substring(1).toLowerCase();
substring is just getting a piece of a larger string, then we are combining them back together.
回答11:
What about WordUtils.capitalizeFully()?
import org.apache.commons.lang3.text.WordUtils;
public class Main {
public static void main(String[] args) {
final String str1 = "HELLO WORLD";
System.out.println(capitalizeFirstLetter(str1)); // output: Hello World
final String str2 = "Hello WORLD";
System.out.println(capitalizeFirstLetter(str2)); // output: Hello World
final String str3 = "hello world";
System.out.println(capitalizeFirstLetter(str3)); // output: Hello World
final String str4 = "heLLo wORld";
System.out.println(capitalizeFirstLetter(str4)); // output: Hello World
}
private static String capitalizeFirstLetter(String str) {
return WordUtils.capitalizeFully(str);
}
}
回答12:
Shortest too:
String message = "my message";
message = Character.toUpperCase(message.charAt(0)) + message.substring(1);
System.out.println(message) // Will output: My message
Worked for me.
回答13:
String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);
回答14:
You can also try this:
String s1 = br.readLine();
char[] chars = s1.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
s1= new String(chars);
System.out.println(s1);
This is better(optimized) than with using substring. (but not to worry on small string)
回答15:
You can use substring()
to do this.
But there are two different cases:
Case 1
If the String
you are capitalizing is meant to be human-readable, you should also specify the default locale:
String firstLetterCapitalized =
myString.substring(0, 1).toUpperCase(Locale.getDefault()) + myString.substring(1);
Case 2
If the String
you are capitalizing is meant to be machine-readable, avoid using Locale.getDefault()
because the string that is returned will be inconsistent across different regions, and in this case always specify the same locale (for example, toUpperCase(Locale.ENGLISH)
). This will ensure that the strings you are using for internal processing are consistent, which will help you avoid difficult-to-find bugs.
Note: You do not have to specify Locale.getDefault()
for toLowerCase()
, as this is done automatically.
回答16:
In Android Studio
Add this dependency to your build.gradle (Module: app)
dependencies {
...
compile 'org.apache.commons:commons-lang3:3.1'
...
}
Now you can use
String string = "STRING WITH ALL CAPPS AND SPACES";
string = string.toLowerCase(); // Make all lowercase if you have caps
someTextView.setText(WordUtils.capitalize(string));
回答17:
Use this utility method to get all first letter in capital.
String captializeAllFirstLetter(String name)
{
char[] array = name.toCharArray();
array[0] = Character.toUpperCase(array[0]);
for (int i = 1; i < array.length; i++) {
if (Character.isWhitespace(array[i - 1])) {
array[i] = Character.toUpperCase(array[i]);
}
}
return new String(array);
}
回答18:
This is just to show you, that you were not that wrong.
BufferedReader br = new InputstreamReader(System.in);
// Assuming name is not blank
String name = br.readLine();
//No more error telling that you cant convert char to string
String s1 = (""+name.charAt(0)).toUppercase());
// Or, as Carlos prefers. See the comments to this post.
String s1 = Character.toString(name.charAt(0)).toUppercase());
System.out.println(s1+name.substring(1));
Note: This is not at all the best way to do it. This is just to show the OP that it can be done using charAt()
as well. ;)
回答19:
This will work
char[] array = value.toCharArray();
array[0] = Character.toUpperCase(array[0]);
String result = new String(array);
回答20:
You can use the following code:
public static void main(String[] args) {
capitalizeFirstLetter("java");
capitalizeFirstLetter("java developer");
}
public static void capitalizeFirstLetter(String text) {
StringBuilder str = new StringBuilder();
String[] tokens = text.split("\\s");// Can be space,comma or hyphen
for (String token : tokens) {
str.append(Character.toUpperCase(token.charAt(0))).append(token.substring(1)).append(" ");
}
str.toString().trim(); // Trim trailing space
System.out.println(str);
}
回答21:
try this one
What this method does is that, Consider the word "hello world" this method turn it into "Hello World" capitalize the beginning of each word .
private String capitalizer(String word){
String[] words = word.split(" ");
StringBuilder sb = new StringBuilder();
if (words[0].length() > 0) {
sb.append(Character.toUpperCase(words[0].charAt(0)) + words[0].subSequence(1, words[0].length()).toString().toLowerCase());
for (int i = 1; i < words.length; i++) {
sb.append(" ");
sb.append(Character.toUpperCase(words[i].charAt(0)) + words[i].subSequence(1, words[i].length()).toString().toLowerCase());
}
}
return sb.toString();
}
回答22:
Given answers is for capitalize the first letter of one word only. use following code to capitalize a whole string.
public static void main(String[] args) {
String str = "this is a random string";
StringBuilder capitalizedString = new StringBuilder();
String[] splited = str.trim().split("\\s+");
for (String string : splited) {
String s1 = string.substring(0, 1).toUpperCase();
String nameCapitalized = s1 + string.substring(1);
capitalizedString.append(nameCapitalized);
capitalizedString.append(" ");
}
System.out.println(capitalizedString.toString().trim());
}
output :
This Is A Random String
回答23:
If Input is UpperCase ,then Use following :
str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
If Input is LowerCase ,then Use following :
str.substring(0, 1).toUpperCase() + str.substring(1);
回答24:
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
How to upper case every first letter of word in a string?
回答25:
public static String capitalizer(final String texto) {
// split words
String[] palavras = texto.split(" ");
StringBuilder sb = new StringBuilder();
// list of word exceptions
List<String> excessoes = new ArrayList<String>(Arrays.asList("de", "da", "das", "do", "dos", "na", "nas", "no", "nos", "a", "e", "o", "em", "com"));
for (String palavra : palavras) {
if (excessoes.contains(palavra.toLowerCase()))
sb.append(palavra.toLowerCase()).append(" ");
else
sb.append(Character.toUpperCase(palavra.charAt(0))).append(palavra.substring(1).toLowerCase()).append(" ");
}
return sb.toString().trim();
}
回答26:
You can use the following code:
public static String capitalizeString(String string) {
if (string == null || string.trim().isEmpty()) {
return string;
}
char c[] = string.trim().toLowerCase().toCharArray();
c[0] = Character.toUpperCase(c[0]);
return new String(c);
}
example test with JUnit:
@Test
public void capitalizeStringUpperCaseTest() {
String string = "HELLO WORLD ";
string = capitalizeString(string);
assertThat(string, is("Hello world"));
}
@Test
public void capitalizeStringLowerCaseTest() {
String string = "hello world ";
string = capitalizeString(string);
assertThat(string, is("Hello world"));
}
回答27:
Using commons.lang.StringUtils
the best answer is:
public static String capitalize(String str) {
int strLen;
return str != null && (strLen = str.length()) != 0 ? (new StringBuffer(strLen)).append(Character.toTitleCase(str.charAt(0))).append(str.substring(1)).toString() : str;
}
I find it brilliant since it wraps the string with a StringBuffer. You can manipulate the StringBuffer as you wish and though using the same instance.
回答28:
Existing answers are either
- incorrect: they think that
char
is a separate character (code point), while it is a UTF-16 word which can be a half of a surrogate pair, or - use libraries which is not bad itself but requires adding dependencies to your project, or
- use Java 8 Streams which is perfectly valid but not always possible.
Let's look at surrogate characters (every such character consist of two UTF-16 words — Java char
s) and can have upper and lowercase variants:
IntStream.rangeClosed(0x01_0000, 0x10_FFFF)
.filter(ch -> Character.toUpperCase(ch) != Character.toLowerCase(ch))
.forEach(ch -> System.out.print(new String(new int[] { ch }, 0, 1)));
Many of them may look like 'tofu' (□) for you but they are mostly valid characters of rare scripts and some typefaces support them.
For example, let's look at Deseret Small Letter Long I (𐐨), U+10428, "\uD801\uDC28"
:
System.out.println("U+" + Integer.toHexString(
"\uD801\uDC28".codePointAt(0)
)); // U+10428
System.out.println("U+" + Integer.toHexString(
Character.toTitleCase("\uD801\uDC28".codePointAt(0))
)); // U+10400 — ok! capitalized character is another code point
System.out.println("U+" + Integer.toHexString(new String(new char[] {
Character.toTitleCase("\uD801\uDC28".charAt(0)), "\uD801\uDC28".charAt(1)
}).codePointAt(0))); // U+10428 — oops! — cannot capitalize an unpaired surrogate
So, a code point can be capitalized even in cases when char
cannot be.
Considering this, let's write a correct (and Java 1.5 compatible!) capitalizer:
@Contract("null -> null")
public static CharSequence capitalize(CharSequence input) {
int length;
if (input == null || (length = input.length()) == 0) return input;
return new StringBuilder(length)
.appendCodePoint(Character.toTitleCase(Character.codePointAt(input, 0)))
.append(input, Character.offsetByCodePoints(input, 0, 1), length);
}
And check whether it works:
public static void main(String[] args) {
// ASCII
System.out.println(capitalize("whatever")); // w -> W
// UTF-16, no surrogate
System.out.println(capitalize("что-то")); // ч -> Ч
// UTF-16 with surrogate pairs
System.out.println(capitalize("\uD801\uDC28")); // 𐐨 -> 𐐀
}
See also:
- surrogate pairs What is a "surrogate pair" in Java?
- upper case vs. title case https://stackoverflow.com/a/47887432/3050249
回答29:
Yet another example, how you can make the first letter of the user input capitalized:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String string = br.readLine();
// handle supplementary characters
IntStream.concat(
IntStream.of(string.codePointAt(0))
.map(Character::toUpperCase), string.codePoints().skip(1)
)
.forEach(cp -> System.out.print(Character.toChars(cp)));
回答30:
Many of the answers are very helpful so I used them to create a method to turn any string to a title (first character capitalized):
static String toTitle (String s) {
String s1 = s.substring(0,1).toUpperCase();
String sTitle = s1 + s.substring(1);
return sTitle;
}
来源:https://stackoverflow.com/questions/3904579/how-to-capitalize-the-first-letter-of-a-string-in-java