如何将字符串中的数字加1? [英] How to increment the number in a String by 1?
问题描述
我在字符串下面有一个-
I have a below String as -
String current_version = "v2";
这里的版本也可以是这些字符串之一- v3
或 v4
或 v10
或 v100
或 v500
或 v1000
And here version can be either of these string as well - v3
or v4
or v10
or v100
or v500
or v1000
现在,我希望将current_version从 v2
增加到 v3
.这意味着我总是需要将current_version增加1.
Now I am looking to increment the current_version from v2
to v3
. Meaning I always need to increment the current_version by 1.
如果current_version是 v5
,那么我将其递增到 v6
.
If current_version is v5
, then I will increment it to v6
.
我该如何使用字符串?
注意:-
我正在从某种方法获取 current_version
字符串值,该方法将始终仅向我返回此v2,v3,v4.
I am getting current_version
string value from some method which will always return me like this v2, v3, v4 only..
推荐答案
如果您想将v后面的数字解析为int并将其递增1,只需通过对字符串进行子串化,将数字加1并将其串联即可.所得的递增数字返回为带"v"前缀的字符串:
If you want to parse the number after the v as an int and increment it by 1, just do so by substringing, adding 1 to the number and concatenating the resulting incremented number back into a string with "v" prepended:
String version = "v1";
String newVersion = "v" + (Integer.parseInt(version.substring(1,version.length()))+1);
System.out.println(newVersion);
或者,您可以在 int
中跟踪当前版本,对其进行递增,并通过将int附加到"v"来构造新的 String
,而无需调用 substring()
.
Alternatively, you could keep track of the current version in an int
, increment that and construct your new String
by appending that int to a "v", without having to call substring()
.
这篇关于如何将字符串中的数字加1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!