简体   繁体   English

将双数替换为字符串中的另一个

[英]Replace double number with another in a string

If I have multiple strings in the following pattern: 如果我有以下模式的多个字符串:

String k = "Remain is 2.5"
String k1 = "Remain is 3.5"
String k2 = "Remain is 4.5"

How can I replace the double number with another?! 如何用另一个替换双数?! It would be a list of strings so number is changed. 这将是一个字符串列表,因此数字会更改。 Also, what's the case if the number's location is changed?! 另外,如果更改号码的位置会怎样?

Example: 例:

String k = "Remain 2.5 pounds"

Any ideas?! 有任何想法吗?!

String.replace seems to fit the bill: String.replace似乎很合适:

String k = "Remain is 2.5"
String k1 = k.replace("2.5", "3.5");
String k2 = k.replace("2.5", "4.5");

If you know that your number is always formatted as a sequence of digits followed by a dot followed by another sequence of digits, and that there is going to be exactly one such sequence per string, you could use replaceAll with regex: 如果您知道您的数字始终被格式化为一个数字序列,然后是一个点,然后是另一个数字序列,并且每个字符串replaceAll恰好有一个这样的序列,那么可以将replaceAll与regex一起使用:

String res = orig.replaceAll("\\d+[.]\\d+", replacementNumberString);

Demo. 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM