我有一个由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 :(得分:4)
试试regexp:
输入:
abcdef
<强>代码:强>
System.out.println("abcdef".replaceAll(".{2}(?!$)", "$0."));
输出
ab.cd.ef
答案 1 :(得分: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);
答案 2 :(得分: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);
答案 3 :(得分: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();
}