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
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);
}
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"
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.
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);
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.
For Java users:
simply a helper method for capitalizing every string.
public static String capitalize(String str)
{
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
After that simply call str = capitalize(str)
For Kotlin users simply call:
str.capitalize()
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.
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);
}
}
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.
String str1 = "hello";
str1.substring(0, 1).toUpperCase()+str1.substring(1);
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.
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));
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)
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. ;)
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);
}
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);
}
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();
}
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
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);
This will work
char[] array = value.toCharArray();
array[0] = Character.toUpperCase(array[0]);
String result = new String(array);
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
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();
}
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;
}
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"));
}
System.out.println(Character.toString(A.charAt(0)).toUpperCase()+A.substring(1));
P.S = a is a string.
To capitalize first character of each word in a string ,
first you need to get each words of that string & for this split string where any space is there using split method as below and store each words in an Array. Then create an empty string. After that by using substring() method get the first character & remaining character of corresponding word and store them in two different variables.
Then by using toUpperCase() method capitalize the first character and add the remaianing characters as below to that empty string.
public class Test {
public static void main(String[] args)
{
String str= "my name is khan"; // string
String words[]=str.split("\\s"); // split each words of above string
String capitalizedWord = ""; // create an empty string
for(String w:words)
{
String first = w.substring(0,1); // get first character of each word
String f_after = w.substring(1); // get remaining character of corresponding word
capitalizedWord += first.toUpperCase() + f_after+ " "; // capitalize first character and add the remaining to the empty string and continue
}
System.out.println(capitalizedWord); // print the result
}
}
The code i have posted will remove underscore(_) symbol and extra spaces from String and also it will capitalize first letter of every new word in String
private String capitalize(String txt){
List<String> finalTxt=new ArrayList<>();
if(txt.contains("_")){
txt=txt.replace("_"," ");
}
if(txt.contains(" ") && txt.length()>1){
String[] tSS=txt.split(" ");
for(String tSSV:tSS){ finalTxt.add(capitalize(tSSV)); }
}
if(finalTxt.size()>0){
txt="";
for(String s:finalTxt){ txt+=s+" "; }
}
if(txt.endsWith(" ") && txt.length()>1){
txt=txt.substring(0, (txt.length()-1));
return txt;
}
txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
return txt;
}
来源:https://stackoverflow.com/questions/3904579/how-to-capitalize-the-first-letter-of-a-string-in-java