Reputation: 31637
I am using Java where I have a string and want to make first letter of word to upper case (each word with comma seperated).
I know using WordUtils.capitalize(str)
it is possible but what I have is as below.
String str = "companies,user,";
I know split
and Wordutils
will do the job, but I am looking for one-liner.
Output looking is one string as
Companies, User
^ ^^
Companies,User
^ ^
Companies,user
^ ^
Upvotes: 1
Views: 2226
Reputation: 13726
Resuable Method for intiCap
public class YarlagaddaSireeshTest{
public static void main(String[] args) {
String FinalStringIs="";
String testNames="Sireesh,Yarlagadda";
String[] name=testNames.split(",");
for(String nameIs :name){
FinalStringIs+=getIntiCapString(nameIs)+","
;
}
System.out.println("Final Result "+ FinalStringIs);
}
public static String getIntiCapString(String param) {
if(param != null && param.length()>0){
char[] charArray = param.toCharArray();
charArray[0] = Character.toUpperCase(charArray[0]);
return new String(charArray);
}else{
return "";
}
}
}
Upvotes: 0
Reputation: 2962
Functional languages like clojure are ideal for this. Since clojure is a jvm language you could evaluate clojure code from within java. Even as a one liner if you are desperate:
RT.var("clojure.core", "eval")
.invoke(RT.var("clojure.core", "read-string")
.invoke(
"(clojure.string/join \", \" " +
"(map clojure.string/capitalize " +
"(clojure.string/split \"companies,user,\" #\",\")))"));
the plain clojure version:
(clojure.string/join
", " (map clojure.string/capitalize
(clojure.string/split "companies,user," #",")))
Honestly, you would never wanna do that! But since you are looking for a one-liner I guess it's worth the fun.
Upvotes: 0
Reputation: 13066
You can try the following in single line !:
String str = "companies,user,";
str = String.valueOf(str.charAt(0)).toUpperCase() + str.substring(1,str.indexOf(","))+
str.substring(str.indexOf(","),str.indexOf(",") + 1) + String.valueOf(str.charAt(str.indexOf(",") + 1)).toUpperCase() + str.substring(str.indexOf(",") + 2);
Upvotes: 3
Reputation: 3780
Quite simply:
String str = "companies,user,";
String strCaps = Character.toUpperCase(str.charAt(0)) + str.substring(1);
Edit: The only way to make it a single line is to make it a method, and use the method, like so:
public static void main(String[] args)
{
String str = "companies,user,";
System.out.println(capitaliseEach(str));
}
static String capitaliseEach(String string)
{
StringBuilder sb = new StringBuilder();
String[] split = string.split(",");
for(int i = 0; i < split.length; i++)
{
if(split[i] != null && split[i].length() >= 2)
{
sb.append(Character.toUpperCase(split[i].charAt(0))).append(split[i].substring(0));
}
if((i + 1) < split.length)
{
sb.append(",");
}
}
return sb.toString();
}
Upvotes: 1