[英]Changing the integer in the String in Java
I need to change the string by decreasing the number by one eg 011 then 010 etc. if 009 then 008. 我需要通过将数字减一来更改字符串,例如011然后010等,如果是009然后008。
However, I cannot think of the ways to do this thing please help me: 但是,我无法想到执行此操作的方法,请帮助我:
<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" />
Here, I want to change files/image006.png
to files/image005.png
and change say files/image010.png
to files/image009.png
. 在这里,我想将
files/image006.png
更改为files/image005.png
,并将例如files/image010.png
更改为files/image009.png
。
PS They are all in strings! PS他们都是弦乐! not HTML tags in fact
实际上不是HTML标签
try regex 尝试正则表达式
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);
int i = Integer.parseInt("011");
System.out.format("%03d", i-1);
Just for funny - scala solution :) 只是为了好玩-Scala解决方案:)
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
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);
EDIT 编辑
To answer your edited question: 要回答您编辑过的问题:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.