我想將任何字符串轉換爲使用某些預定義庫而不是編寫自己的函數的修改後的駱駝案例或標題案例。將字符串轉換爲Java或標題案例中的修改後的駱駝案例否則稱爲
例如"HI tHiS is SomE Statement"
到"Hi This Is Some Statement"
正則表達式或任何標準庫將幫助我。
我在eclipse中發現了某些庫函數,如STRING.toCamelCase();
有沒有這樣的東西存在?
我想將任何字符串轉換爲使用某些預定義庫而不是編寫自己的函數的修改後的駱駝案例或標題案例。將字符串轉換爲Java或標題案例中的修改後的駱駝案例否則稱爲
例如"HI tHiS is SomE Statement"
到"Hi This Is Some Statement"
正則表達式或任何標準庫將幫助我。
我在eclipse中發現了某些庫函數,如STRING.toCamelCase();
有沒有這樣的東西存在?
我用下面的來解決這個問題。
import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);
感謝泰德·霍普爲正確地指出的問題應該是標題大寫,而不是修改CAMEL CASE。
駱駝案件通常在單詞之間沒有空格。
你可以很容易地編寫方法來做到這一點:
public static String toCamelCase(final String init) {
if (init==null)
return null;
final StringBuilder ret = new StringBuilder(init.length());
for (final String word : init.split(" ")) {
if (!word.isEmpty()) {
ret.append(word.substring(0, 1).toUpperCase());
ret.append(word.substring(1).toLowerCase());
}
if (!(ret.length()==init.length()))
ret.append(" ");
}
return ret.toString();
}
而不是'word.substring(0,1).toUpperCase()'你可以做'Character.toUpperCase(word.charAt(0))' – fge
org.apache.commons.lang3.text.WordUtils.capitalizeFully(String str)
static String toCamelCase(String s){
String[] parts = s.split(" ");
String camelCaseString = "";
for (String part : parts){
if(part!=null && part.trim().length()>0)
camelCaseString = camelCaseString + toProperCase(part);
else
camelCaseString=camelCaseString+part+" ";
}
return camelCaseString;
}
static String toProperCase(String s) {
String temp=s.trim();
String spaces="";
if(temp.length()!=s.length())
{
int startCharIndex=s.charAt(temp.indexOf(0));
spaces=s.substring(0,startCharIndex);
}
temp=temp.substring(0, 1).toUpperCase() +
spaces+temp.substring(1).toLowerCase()+" ";
return temp;
}
public static void main(String[] args) {
String string="HI tHiS is SomE Statement";
System.out.println(toCamelCase(string));
}
這段代碼如果有兩個連續的字符會拋出一個StringIndexOutOfBoundsException String中的空格(或者如果String是空的)。如果'String'爲null,它會拋出'NullPointerException'。 –
@FlorentBayle哦,讓看到更新的答案! – NFE
也許你的意思是[title case](http://en.wikipedia.org/wiki/Sentence_case#Title_case)? 「[駱駝案件](http://en.wikipedia.org/wiki/CamelCase)」通常指像「HiThisIsSomeStatement」這樣的詞(詞之間沒有分隔符)。 –
對不起,我不知道標題案例。謝謝泰德霍普。我想要Title Case – takrishna