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.

提前致谢:)

4

4 回答 4

4

尝试正则表达式:

输入:

abcdef

代码:

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

输出:

ab.cd.ef
于 2013-05-03T08:47:02.180 回答
1

您应该将其修复为

    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);
于 2013-05-03T08:46:34.237 回答
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);
于 2013-05-03T08:40:55.377 回答
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();
}
于 2013-05-03T08:43:29.220 回答