Frage

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..

War es hilfreich?

Lösung

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);

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().

Andere Tipps

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;

try

int version = Integer.parseInt(current_version.replace("v", ""));

then you can increment it and add a get "v" + current_version

If your format ever changes, this allows for a bit more flexibility:

String version = "v1234";
System.out.println("v" + (Integer.parseInt(version.replaceAll("[^0-9]", "")) + 1));

Use a regex to drop all non-digits, add one to the result.

    String oldVersion = "v100";
    String[] splitString = oldVersion.split("v");
    int newVersion = Integer.valueOf(splitString[1])+1;
    String completeNewVersion = splitString[0] + newVersion;
    System.out.print(completeNewVersion);

Why you don't store the version as an int and add the char 'v' when displaying the version? If you wish to do it with a String, you can make a substring of the initial one, parse it to int and after that add to'v' the result.

 currentVersion = "v" + (Integer.parseInt(currentVersion .substring(1)) + 1);

If you want another solution you can use this :

uint8_t versionNumber = 1;
char version[40];
sprintf(version,"v %d",versionNumber);

And you increment your variable "versionNumber" whenever you want !

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top