How to increment the number in a String by 1?

user2467545 picture user2467545 · Feb 21, 2014 · Viewed 50.8k times · Source

I have a below String as -

String current_version = "v2";

And here version can be either of these string as well - v3 or v4 or v10 or v100 or v500 or v1000

Now I am looking to increment the current_version from v2 to v3. Meaning I always need to increment the current_version by 1.

If current_version is v5, then I will increment it to v6.

How can I do this with a String?

NOTE:-

I am getting current_version string value from some method which will always return me like this v2, v3, v4 only..

Answer

stinepike picture stinepike · Feb 21, 2014

I will suggest you to store the version in an int. so the codes will be following

int versionNumber = 1;

whenever you want to increment just increment it using

versionNumber++;

and to print or store as a complete version do following

String version = "v" + versionNumber;