我需要通过将数字减少一个来更改字符串,例如如果009然后是008,那么011然后是010等。
然而,我无法想到做这件事的方法请帮助我:
<img width="188" height="307" src="File1.files/image006.png" alt="NNMF_Input.png" v:shapes="image_x0020_33" />
<img width="506" height="200" src="File1.files/image014.png" v:shapes="image_x0020_1" />
<img width="506" height="411" src="File1.files/image016.png" v:shapes="image_x0020_2" />
<img width="515" height="179" src="File1.files/image018.png" v:shapes="image_x0020_3" />
在此,我想将files/image006.png
更改为files/image005.png
并更改说明
files/image010.png
到files/image009.png
。
P.S。他们都是弦乐!实际上不是HTML标签
答案 0 :(得分:6)
尝试正则表达式
Matcher m = Pattern.compile("(?<=/image)\\d{3}").matcher(str);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, String.format("%03d", Integer.parseInt(m.group()) - 1));
}
m.appendTail(sb);
答案 1 :(得分:0)
int i = Integer.parseInt("011");
System.out.format("%03d", i-1);
答案 2 :(得分:0)
只是为了搞笑 - 斯卡拉解决方案:)
scala> def increment(str:String) = str.split("[^0-9]").
filter( s => s.nonEmpty && s.length >1).
foldLeft(str)((acc,curr) => acc.replace(curr, {val res = (curr.toInt+1).toString;Range(0,curr.length - res.length).
foldLeft(res)((acc,curr)=> "0"+acc) }))
increment: (str: String)String
scala> increment("File1.files/image014.png")
res10: String = File1.files/image015.png
答案 3 :(得分:0)
String str = "000110";
// Get the last index and add 1 to determine number of leading zeros
int i = str.lastIndexOf('0') + 1;
// Subtract or do any math on the number you want
int newNumber = Integer.parseInt(str) - 1;
// Format the new string with leading zeros
String newString = String.format("%0" + i + "d", newNumber);
// See the new string
System.out.println(newString);
修改强>
回答您编辑过的问题:
String str = "image0110";
// Get the number (above example 0110) from original string using the last character 'e 'from 'image'
str = str.substring(str.lastIndexOf('e') + 1);
// Get how many leading zeros are in there
int i = str.lastIndexOf('0') + 1;
// Do the math
int newNumber = Integer.parseInt(str) - 1;
// Form the new string starting with 'image' and leading zeros
String newString = "image" + String.format("%0" + i + "d", newNumber);
System.out.println(newString);