2013-05-03 4 views
3

6 개의 문자 (예 : "abcdef")로 구성된 문자열이 있습니다. "."을 추가해야합니다. 두 글자마다 "ab.cd.ef"와 같이 될 것입니다. 나는 자바에서 일하고 있어요, 나는이 시도 :특정 인덱스의 문자열에 문자를 추가하는 방법은 무엇입니까?

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/)를 게시하십시오. –

답변

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); 

또한 정규식과 같은 작업을 수행 할 수 있습니다로 수정해야합니다, 그것은 하나 라인 솔루션

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

+0

@Hanady 나는 내 대답을 편집했다. –

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 
관련 문제