【发布时间】:2019-06-11 08:04:24
【问题描述】:
我正在编写一个程序来获取字符串的不同部分,例如“10 万亿 8370 亿 4500 万 56739”。我问了这个问题here。 但有时我的字符串会变成“10 万亿 8370 亿 4500 万 56 739”。 我想删除“56 739”中 6 到 7 之间的空格。
我知道要删除空格,但不知道如何指定哪些字符是要删除的空格
这是我的代码
String input = "10 trillion 837 billion 45 million 56 739";
String pattern = "\\s\\d"; // this will match space and number thus will give you start of each number.
ArrayList<Integer> inds = new ArrayList<Integer>();
ArrayList<String> strs = new ArrayList<String>();
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
while (m.find()) {
inds.add(m.start()); //start will return starting index.
}
//iterate over start indexes and each entry in inds array list will be the end index of substring.
//start index will be 0 and for subsequent iterations it will be end index + 1th position.
int indx = 0;
for(int i=0; i <= inds.size(); i++) {
if(i < inds.size()) {
strs.add(input.substring(indx, inds.get(i)));
indx = inds.get(i)+1;
} else {
strs.add(input.substring(indx, input.length()));
}
}
for(int i =0; i < strs.size(); i++) {
Toast.makeText(getApplicationContext(),strs.get(i)+"",Toast.LENGTH_LONG).show();
}
我尝试添加这样的 replaceAll 语句input = input.replaceAll("\\d\\s\\d","\\d\\d"); 但它不起作用
【问题讨论】: