Input >
user_input = 123456789
format = "xx-xxx-x-xx-x"
Output >
12-345-6-78-9
或者
Input >
user_input = 123456
format = "x-xx-x-x-x"
Output >
1-23-4-5-6
我尽我所能并尝试使用其他语言(python,js) 但它不起作用。
it have problem after else statement
String a = "123456";
String b = "xxx-xx-x";
char[] c_arr = b.toCharArray();
for (int i = 0; i < b.length(); i++) {
if(c_arr[i] != '-'){
c_arr[i] = a.charAt(i);
} else {
c_arr[i+1] = a.charAt(i);
}
System.out.println(c_arr);
}
答案 0 :(得分:1)
这里的代码可以解决您的问题。发生的事情是你的计数器变量超过了a
字符串的长度。要解决这个问题,请使用一个单独的计数器,该计数器遍历该字符串,该字符串随着字符的消耗而递增。
String a = "123456";
String b = "xxx-xx-x";
char[] cArray = b.toCharArray();
int aPos = 0; // create separate counter
for (int i = 0; i < b.length(); i++) {
if (cArray[i] == '-') continue; // if skipping, do not increment aPos, continue
cArray[i] = a.charAt(aPos);
aPos++; // add counter when we used the charAt
System.out.println(cArray);
}
但是,这仍然可能会中断,因为b
中需要填充的位置可能比a
中的可消耗字符更多。如果输入不匹配,我建议进行运行时检查以抛出异常。