2013-05-03 79 views
3

我有一個由6個字母組成的字符串,例如:「abcdef」。 我需要添加「。」每兩個字符,所以它會是這樣的:「ab.cd.ef」。 我在java中工作,我嘗試這樣做:如何將字符添加到特定索引中的字符串?

private String FormatAddress(String sourceAddress) { 
    char[] sourceAddressFormatted = new char[8]; 
    sourceAddress.getChars(0, 1, sourceAddressFormatted, 0); 
    sourceAddress += "."; 
    sourceAddress.getChars(2, 3, sourceAddressFormatted, 3); 
    sourceAddress += "."; 
    sourceAddress.getChars(4, 5, sourceAddressFormatted, 6); 
    String s = new String(sourceAddressFormatted); 
    return s; 
} 

但是我收到奇怪的值,比如[C @ 2723b6。

感謝提前:)

+0

爲了儘快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 – 2013-05-03 08:37:27

回答

2

你應該修復它作爲

String sourceAddress = "abcdef"; 
    String s = sourceAddress.substring(0, 2); 
    s += "."; 
    s += sourceAddress.substring(2, 4); 
    s += "."; 
    s += sourceAddress.substring(4, 6); 
    System.out.println(s); 

你也可以做正則表達式一樣,它是一個line solution

String s = sourceAddress.replaceAll("(\\w\\w)(?=\\w\\w)", "$1."); 
    System.out.println(s); 
0

試試這個:

String result=""; 
String str ="abcdef"; 
for(int i =2; i<str.length(); i=i+2){ 
    result = result + str.substring(i-2 , i) + "."; 
} 
result = result + str.substring(str.length()-2); 
+0

最後兩個字母不會以這種方式添加。 – Hanady 2013-05-03 09:05:26

+0

@Hanady我現在編輯我的答案。 – 2013-05-03 09:42:20

0
private String formatAddress(String sourceAddress) { 
    StringBuilder sb = new StringBuilder(); 
    for (int i = 0; i < sourceAddress.length(); i+=2) { 
     sb.append(sourceAddress.substring(i, i+2)); 
     if (i != sourceAddress.length()-1) { 
      sb.append('.'); 
     } 
    } 
    return sb.toString(); 
} 
4

嘗試正則表達式:

輸入:

abcdef 

代碼:

System.out.println("abcdef".replaceAll(".{2}(?!$)", "$0.")); 

輸出:

ab.cd.ef 
相關問題