2012-01-25 34 views
0

假設我有如下兩個字符串:如何在Java中修改此字符串?

String name = "EXAMPLE_MODEL_1"; 
String actionName = "ListModels"; 

我想要得到的字符串如下:

String result = "ExampleModel1ListModels"; 

我試過Follwoing代碼:

String result = name.toLowerCase().replaceAll("_", ""); 
result = result.concat(actioName); 

而且我得到了結果值爲「examplemodel1ListModels」。但是,其中一個是「ExampleModel1ListModels」。

+0

我不明白烏爾Q,烏爾得到什麼ü預期的,請糾正錯別字如果u有任何 –

+0

我可能是錯誤,但如果我正確理解這個'toLowerCase'應該將結果轉換爲小寫。這難道不能解釋你爲什麼沒有獲得最初的大寫結果嗎? –

+0

它由@lucifer編輯有一個錯字例子是實例 –

回答

1

您正在使用toLowerCase()方法,因此您得到的結果如此。請勿使用此功能。

+0

然後使用哪個函數? – Beginner

+0

@Beginner你需要找到一些函數來將你的String轉換爲Title Case而不是小寫。 – gprathour

3

name字符串需要替換下劃線 - 你已經這樣做了。在你這樣做之前,你需要convert it to title case

之後,簡單地連接兩個字符串。

0

利用番石榴的CaseFormat

String result = LOWER_UNDERSCORE.to(UPPER_CAMEL, "EXAMPLE_MODEL_1") + "ListModels"; 
0

阿帕奇公地朗工具類,可以幫助你。下面是我的想法

  1. 轉換名小case
  2. 使用字符串capitalizeFully(字符串str的char []分隔符)用分隔符爲_
  3. 從步出結果刪除空格1
  4. 串連兩
0

嘗試使用下面的代碼(我編輯並粘貼完整的代碼)

import java.io.IOException; 
public class StringTest{ 

    public static void main(String[] arg) throws IOException{ 
     String name = "EXAMPLE_MODEL_1"; String actionName = "ListModels"; 
     String result = toProperCase(name.toLowerCase().replaceAll("_", " "))+actionName; 
     result= result.replaceAll(" ",""); 
     System.out.println(result); 

    } 
    public static String toProperCase(String theString) throws java.io.IOException{ 
     java.io.StringReader in = new java.io.StringReader(theString.toLowerCase()); 
     boolean precededBySpace = true; 
     StringBuffer properCase = new StringBuffer();  
      while(true) {  
      int i = in.read(); 
       if (i == -1) break;  
       char c = (char)i; 
       if (c == ' ' || c == '"' || c == '(' || c == '.' || c == '/' || c == '\\' || c == ',') { 
        properCase.append(c); 
        precededBySpace = true; 
       } else { 
        if (precededBySpace) { 
       properCase.append(Character.toUpperCase(c)); 
       } else { 
        properCase.append(c); 
       } 
       precededBySpace = false; 
      } 
      } 

     return properCase.toString();  

    } 
}