Example strings
one thousand only
two hundred
twenty
seven
How do I change the first character of a string in capital letter and not change
Example using StringTokenizer class :
String st = " hello all students";
String st1;
char f;
String fs="";
StringTokenizer a= new StringTokenizer(st);
while(a.hasMoreTokens()){
st1=a.nextToken();
f=Character.toUpperCase(st1.charAt(0));
fs+=f+ st1.substring(1);
System.out.println(fs);
}
if you only want to capitalize the first letter then the below code can be used
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Actually, you will get the best performance if you avoid +
operator and use concat()
in this case. It is the best option for merging just 2 strings (not so good for many strings though). In that case the code would look like this:
String output = input.substring(0, 1).toUpperCase().concat(input.substring(1));
substring()
Methodpublic static String capitalize(String str) {
if(str== null || str.isEmpty()) {
return str;
}
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
Now just call the capitalize()
method to convert the first letter of a string to uppercase:
System.out.println(capitalize("stackoverflow")); // Stackoverflow
System.out.println(capitalize("heLLo")); // HeLLo
System.out.println(capitalize(null)); // null
The StringUtils
class from Commons Lang provides the capitalize()
method that can also be used 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
Add the following dependency to your pom.xml
file (for Maven only):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
Here is an article that explains these two approaches in detail.
If you only want to capitalize the first letter of a string named input
and leave the rest alone:
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
Now output
will have what you want. Check that your input
is at least one character long before using this, otherwise you'll get an exception.
String s=t.getText().trim();
int l=s.length();
char c=Character.toUpperCase(s.charAt(0));
s=c+s.substring(1);
for(int i=1; i<l; i++)
{
if(s.charAt(i)==' ')
{
c=Character.toUpperCase(s.charAt(i+1));
s=s.substring(0, i) + c + s.substring(i+2);
}
}
t.setText(s);