我正在尝试查找以下的Java代码:
1)检查String是否包含任何连续的整数
2)如果它包含连续的整数,则连接它们,即我当前的消息只有空格分隔的整数,所以我需要一种方法来连接那些空格分开的整数。例如:
message1 = "My no is 9543 21 00 10"
desired output = "My no is 9543210010"
message2 = "You can reach 2 me at 42315 468"
desired output = "You can reach 2 me at 42315468"
我的主要问题是为电话号码解决上述问题,即将空格分隔的电话号码连接在一起,所以如果有人有不同的解决方法,请告诉我。
我尝试了以下代码,但是当字符串以空格结尾时它不起作用:
if(message.matches(".*\\d.*")){
for (int i = 0; i <= message.length() -2 ; ++i){
if ((Character.isDigit(message.charAt(i))) && message.charAt(i+1) == ' ' && (Character.isDigit(message.charAt(i+2)))) {
StringBuilder sb = new StringBuilder(message);
sb.deleteCharAt(i+1);
message = sb.toString();
}
}
}
答案 0 :(得分:1)
基于peshmo评论的社区维基答案。
换句话说,您正在尝试删除数字包围的空格。
//For country
$("#country").appened('<option value="' + data.Text + '">' + data.Text + '</option>');
//For States
$("#province").appened('<option value="' + state.Text + '">' + state.Text + '</option>');
// For city (I assume that the dataitem name is 'city' here.
$("#city").appened('<option value="' + city.Text + '">' + city.Text + '</option>');
这个正则表达式将会这样做。在这里试试:https://regex101.com/r/qR33XN/1
答案 1 :(得分:0)
这是未经测试的代码,只是用记事本写的,但我想你会得到这个要点。
基本上,将字符串拆分为一个带有空格('')分隔符的数组,将所有内容粘合在一起。如果index + 1不是数字,则添加空格,否则不添加空格。
我希望这会有所帮助
String msg = "abc 1 2 3 333 yoo"
String[] splitted = msg.Split(' ');
String output = "";
for(int i = 0; i < splitted.Length - 1; i++) {
output += splitted[i];
if(i + 1 < splitted.Length - 1) {
if(isInteger(splitted[i]) && isInteger(splitted[i+1]))
continue;
}
output += " "
}
output = output.Trim();
public static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
// only got here if we didn't return false
return true;
}