如何将字符添加到特定索引中的字符串?
问题描述:
我有一个由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。
感谢提前:)
答
你应该修复它作为
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);
答
试试这个:
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
答
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();
}
答
尝试正则表达式:
输入:
abcdef
代码:
System.out.println("abcdef".replaceAll(".{2}(?!$)", "$0."));
输出:
ab.cd.ef
为了尽快提供更好的帮助,请发布[SSCCE](http://sscce.org/)。 – 2013-05-03 08:37:27