As of now I\'m using this code to make my first letter in a string capital
String output = input.substring(0, 1).toUpperCase() + input.substring(1);
<
You should have a look at StringUtils class from Apache Commons Lang lib - it has method .capitalize()
Description from the lib:
Capitalizes a String changing the first letter to title case as per Character.toTitleCase(char). No other letters are changed.
Character.toString(a.charAt(0)).toUpperCase()+a.substring(1)
P.S = a is string.
Here, hold my beer
String foo = "suresh";
String bar = foo.toUpperCase();
if(bar.charAt[0] == 'S'){
throw new SuccessException("bar contains 'SURESH' and has the first letter capital").
}
Assuming you can use Java 8, here's the functional way that nobody asked for...
import java.util.Optional;
import java.util.stream.IntStream;
public class StringHelper {
public static String capitalize(String source) {
return Optional.ofNullable(source)
.map(str -> IntStream.concat(
str.codePoints().limit(1).map(Character::toUpperCase),
str.codePoints().skip(1)))
.map(stream -> stream.toArray())
.map(arr -> new String(arr, 0, arr.length))
.orElse(null);
}
}
It's elegant in that it handles the null and empty string cases without any conditional statements.
How about this:
String output = Character.toUpperCase(input.charAt(0)) + input.substring(1);
I can't think of anything cleaner without using external libraries, but this is definitely better than what you currently have.
class strDemo3
{
public static void main(String args[])
{
String s1=new String(" the ghost of the arabean sea");
char c1[]=new char[30];
int c2[]=new int[30];
s1.getChars(0,28,c1,0);
for(int i=0;i<s1.length();i++)
{
System.out.print(c1[i]);
}
for(int i=1;i<s1.length();i++)
{
c2[i]=c1[i];
if(c1[i-1]==' ')
{
c2[i]=c2[i]-32;
}
c1[i]=(char)c2[i];
}
for(int i=0;i<s1.length();i++)
{
System.out.print(c1[i]);
}
}
}