Reputation: 5159
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
Upvotes: 515
Views: 1044363
Reputation: 1
Use this utility method to capitalize the first letter of every word.
String capitalizeAllFirstLetters(String name)
{
char[] array = name.toLowerCase().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);
}
Upvotes: 14
Reputation: 2737
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();
}
Upvotes: 4
Reputation: 8760
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)
Upvotes: 6
Reputation: 125
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.
Upvotes: 11
Reputation: 37
To avoid exceptions (IndexOutOfBoundsException or NullPointerException when using substring(0, 1) for an empty or null string), you can use regex ("^.") (since Java 9):
try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
String name = reader.readLine();
name = Pattern.compile("^.") // regex for the first character of a string
.matcher(name)
.replaceFirst(matchResult -> matchResult.group().toUpperCase());
System.out.println(name);
} catch(IOException ignore) {}
Upvotes: -1
Reputation: 25261
Step 1:
Import apache's common lang library by putting this in build.gradle
dependencies
implementation '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.
Upvotes: 104
Reputation: 1708
Simple solution! doesn't require any external library, it can handle empty or one letter string.
private String capitalizeFirstLetter(@NonNull String str){
return str.length() == 0 ? str
: str.length() == 1 ? str.toUpperCase()
: str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
}
Upvotes: 6
Reputation: 22138
Java:
simply a helper method for capitalizing every string.
public static String capitalize(String str)
{
if(str == null || str.length()<=1) return str;
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
After that simply call str = capitalize(str)
Kotlin:
str.capitalize()
Upvotes: 45
Reputation: 672
char
can't store in String
.char
and String
can't concatenate.String.valueOf()
use to convert char
to String
Input
india
Code
String name = "india";
char s1 = name.charAt(0).toUppercase()); // output: 'I'
System.out.println(String.valueOf(s1) + name.substring(1)); // output: "I"+ "ndia";
Output
India
Upvotes: -1
Reputation: 565
You can use substrings for simple hacks ;).
String name;
String s1 = name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
System.out.println(s1));
Upvotes: 2
Reputation: 31
Since you first get Char from your original string. You cant use String properties on char so just use to upper first and then use charAt
String s1 = name.toUppercase().charAt(0);
Upvotes: 2
Reputation: 535
Here is solution from my side, with all the conditions check.
import java.util.Objects;
public class CapitalizeFirstCharacter {
public static void main(String[] args) {
System.out.println(capitailzeFirstCharacterOfString("jwala")); //supply input string here
}
private static String capitailzeFirstCharacterOfString(String strToCapitalize) {
if (Objects.nonNull(strToCapitalize) && !strToCapitalize.isEmpty()) {
return strToCapitalize.substring(0, 1).toUpperCase() + strToCapitalize.substring(1);
} else {
return "Null or Empty value of string supplied";
}
}
}
Upvotes: 0
Reputation: 10890
import static org.springframework.util.StringUtils.capitalize;
...
return capitalize(name);
IMPLEMENTATION: org/springframework/util/StringUtils.java#L535-L555
REF: javadoc-api/org/springframework/util/StringUtils.html#capitalize
NOTE: If you already have Apache Common Lang dependency, then consider using their StringUtils.capitalize as other answers suggest.
Upvotes: 48
Reputation: 1868
To capitalize the first letter of the input string, we first split the string on space and then use the collection transformation procedure provided by map
<T, R> Array<out T>.map(
transform: (T) -> R
): List<R>
to transform, each split string to first in lowercase then capitalize the first letter. This map transformation will return a list that needs to convert into a string by using joinToString function.
KOTLIN
fun main() {
/*
* Program that first convert all uper case into lower case then
* convert fist letter into uppercase
*/
val str = "aLi AzAZ alam"
val calStr = str.split(" ").map{it.toLowerCase().capitalize()}
println(calStr.joinToString(separator = " "))
}
OUTPUT
Upvotes: 0
Reputation: 5261
Here is my detailed article on the topic for all possible options Capitalize First Letter of String in Android
Method to Capitalize First Letter of String in Java
public static String capitalizeString(String str) {
String retStr = str;
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
}catch (Exception e){}
return retStr;
}
Method to Capitalize First Letter of String in KOTLIN
fun capitalizeString(str: String): String {
var retStr = str
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
} catch (e: Exception) {
}
return retStr
}
Upvotes: 8
Reputation: 327
IT WILL WORK 101%
public class UpperCase {
public static void main(String [] args) {
String name;
System.out.print("INPUT: ");
Scanner scan = new Scanner(System.in);
name = scan.next();
String upperCase = name.substring(0, 1).toUpperCase() + name.substring(1);
System.out.println("OUTPUT: " + upperCase);
}
}
Upvotes: 7
Reputation: 2913
Current answers are either incorrect or over-complicate this simple task. After doing some research, here are two approaches I come up with:
1. String's substring()
Method
public static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
Examples:
System.out.println(capitalize("java")); // Java
System.out.println(capitalize("beTa")); // BeTa
System.out.println(capitalize(null)); // null
2. Apache Commons Lang
The Apache Commons Lang library provides StringUtils
the class for this purpose:
System.out.println(StringUtils.capitalize("apache commons")); // Apache commons
System.out.println(StringUtils.capitalize("heLLO")); // HeLLO
System.out.println(StringUtils.uncapitalize(null)); // null
Don't forget to add the following dependency to your pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Upvotes: 4
Reputation:
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)));
Upvotes: 2
Reputation: 6363
Existing answers are either
char
is a separate character (code point), while it is a UTF-16 word which can be a half of a surrogate pair, orLet'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:
Upvotes: 4
Reputation: 2066
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.
Upvotes: 3
Reputation: 1
import java.util.*;
public class Program
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String s1=sc.nextLine();
String[] s2=s1.split(" ");//***split text into words***
ArrayList<String> l = new ArrayList<String>();//***list***
for(String w: s2)
l.add(w.substring(0,1).toUpperCase()+w.substring(1));
//***converting 1st letter to capital and adding to list***
StringBuilder sb = new StringBuilder();//***i used StringBuilder to convert words to text***
for (String s : l)
{
sb.append(s);
sb.append(" ");
}
System.out.println(sb.toString());//***to print output***
}
}
i have used split function to split the string into words then again i took list to get the first letter capital in that words and then i took string builder to print the output in string format with spaces in it
Upvotes: 0
Reputation: 430
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);
Upvotes: 4
Reputation: 11
Use replace method.
String newWord = word.replace(String.valueOf(word.charAt(0)), String.valueOf(word.charAt(0)).toUpperCase());
Upvotes: 1
Reputation: 880
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
Upvotes: 1
Reputation: 21
One of the answers was 95% correct, but it failed on my unitTest @Ameen Maheen's solution was nearly perfect. Except that before the input gets converted to String array, you have to trim the input. So the perfect one:
private String convertStringToName(String name) {
name = name.trim();
String[] words = name.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();
}
Upvotes: 1
Reputation: 13
This code to capitalize each word in text!
public String capitalizeText(String name) {
String[] s = name.trim().toLowerCase().split("\\s+");
name = "";
for (String i : s){
if(i.equals("")) return name; // or return anything you want
name+= i.substring(0, 1).toUpperCase() + i.substring(1) + " "; // uppercase first char in words
}
return name.trim();
}
Upvotes: 0
Reputation: 208
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;
}
Upvotes: 1
Reputation: 13083
One approach.
String input = "someТекст$T%$4čřЭ"; //Enter your text.
if (input == null || input.isEmpty()) {
return "";
}
char [] chars = input.toCharArray();
chars[0] = chars[0].toUpperCase();
String res = new String(chars);
return res;
The drawback of this method is that if inputString is long, you will have three objects of such length. The same as you do
String s1 = input.substring(1).toUpperCase();
String s2 = input.substring(1, lenght);
String res = s1 + s2;
Or even
//check if not null.
StringBuilder buf = new StringBuilder(input);
char ch = buf.getCharAt(0).toUpperCase();
buf.setCharAt(0, ch);
return buf.toString();
Upvotes: 0
Reputation: 361
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.
Upvotes: 16
Reputation: 1939
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
}
}
Upvotes: 1