字符串中的增量数字值 [英] Increment digit value in String

查看:45
本文介绍了字符串中的增量数字值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一些带有数字和另一个符号的字符串,并且我想将每个数字的值增加为1.例如:从该字符串中获取"test1check2",我想接收"test2check3".我只能使用方法"replaceAll"来做到这一点吗?(i.replaceAll("\ d",...)类似的东西)吗?,而无需使用诸如indexOf,charAt ...

So, i have some String with digits and another symbols, and i want to increment the value of each digit at 1. For example: "test1check2" from this String i want to recieve "test2check3". And can i make this only with method "replaceAll"? (i.replaceAll("\d", ...) something like that)?, without to use methods such like indexOf, charAt...

推荐答案

我不认为您可以使用简单的replaceAll(...)来做到这一点,您必须编写几行代码:

I don't think you can do it with a simple replaceAll(...), you'll have to write a few lines like:

Pattern digitPattern = Pattern.compile("(\\d)"); // EDIT: Increment each digit.

Matcher matcher = digitPattern.matcher("test1check2");
StringBuffer result = new StringBuffer();
while (matcher.find())
{
    matcher.appendReplacement(result, String.valueOf(Integer.parseInt(matcher.group(1)) + 1));
}
matcher.appendTail(result);
return result.toString();

这里可能存在一些语法错误,但可以正常工作.

There's probably some syntax errors here, but it will work something like that.

您评论了每个数字都必须分别递增(abc12d-> abc23d),以便将模式从(\\ d +)更改为(\\ d)

You commented that each digit must be incremented separately (abc12d -> abc23d) so the pattern should be changed from (\\d+) to (\\d)

根据 Matcher 类的要求,将 StringBuilder 更改为 StringBuffer .

EDIT 2: Change StringBuilder to StringBuffer as required by Matcher class.

这篇关于字符串中的增量数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆