2011-02-03 64 views
18

如何隱蔽"HelloWorld""Hello World" .The分裂具有基於大寫字母發生,但應排除的第一個字母。插入空格後大寫字母

P.S:我知道使用String.split然後合併。只是想知道是否有更好的方法。

+0

作爲評論發佈而不是回答,因爲我不知道 句法。但我敢肯定,這將是很容易寫的正則表達式會尋找一個大寫字母(是不是在句子的開頭)和前添加一個空格。 – DaveJohnston 2011-02-03 12:27:09

+1

您是否期望`convert(「HELLO」)==「H E L L O」`? – vz0 2011-02-03 12:27:18

+0

@ vz0:其實我的字符串在大寫字母之間會有一些小寫字母。 – Emil 2011-02-03 12:29:39

回答

57
String output = input.replaceAll("(\\p{Ll})(\\p{Lu})","$1 $2"); 

由大寫字母follwed小寫字母此正則表達式搜索和同前,一個空間,而後者(有效用空格分隔它們)替換它們。它在爲了能夠在經由反向引用($1$2)替換字符串來重新使用的值使它們中的每一個捕獲組()

要找到大寫和小寫字母,它使用\p{Ll}\p{Lu}(而不是[a-z][A-Z]),因爲它處理Unicode標準中的所有大寫和小寫字母,而不僅僅是在ASCII範圍內的那些(this nice explanation of Unicode in regexes大多數也適用於Java)。

+0

+1確實聰明的解決方案! – Nishant 2011-02-03 13:08:50

1

如果你不想使用正則表達式,你可以通過字符串中的字符循環,把它們添加到一個StringBuilder(並添加一個空格字符串生成器,如果你遇到一個大寫字母,這不是第一個) :

String s = "HelloWorld"; 
StringBuilder result = new StringBuilder(); 
for(int i=0 ; i<s.length() ; i++) { 
    char c = s.charAt(i); 
    if(i!=0&&Character.isUpperCase(c)) { 
     result.append(' '); 
    } 
    result.append(c); 
} 
0

僞代碼:

String source = ...; 
String result = ""; 

// FIXME: check for enf-of-source 

for each letter in source { 
    while current letter not uppercase { 
     push the letter to result; 
     advance one letter; 
    } 
    if not the first letter { 
     push space to result; 
    } 
    push the letter to result; 
} 
4

更好是主觀的。這需要一些代碼多行:

public static String deCamelCasealize(String camelCasedString) { 
    if (camelCasedString == null || camelCasedString.isEmpty()) 
     return camelCasedString; 

    StringBuilder result = new StringBuilder(); 
    result.append(camelCasedString.charAt(0)); 
    for (int i = 1; i < camelCasedString.length(); i++) { 
     if (Character.isUpperCase(camelCasedString.charAt(i))) 
     result.append(" "); 
     result.append(camelCasedString.charAt(i)); 
    } 
    return result.toString(); 
} 

隱藏這個醜陋的實施工具類,並用它作爲一個API(看起來從用戶角度確定;))

2
String s = "HelloWorldNishant"; 
    StringBuilder out = new StringBuilder(s); 
    Pattern p = Pattern.compile("[A-Z]"); 
    Matcher m = p.matcher(s); 
    int extraFeed = 0; 
    while(m.find()){ 
     if(m.start()!=0){ 
      out = out.insert(m.start()+extraFeed, " "); 
      extraFeed++; 
     } 
    } 
    System.out.println(out); 

打印

Hello World Nishant

相關問題