Increment digit value in String

So, I have a line with numbers and other characters, and I want to increase the value of each digit by 1. For example: "test1check2" from this line I want to get "test2check3". And can I do this only with the replaceAll method? (i.replaceAll ("\ d", ...) something like this) ?, without using methods like indexOf, charAt ...

+4
source share
2 answers

I don’t think you can do this with a simple replaceAll (...), you have to write a few lines, for example:

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 are probably some syntax errors here, but they will work something like this.

EDIT:. You commented that each digit must be increased separately (abc12d β†’ abc23d) so that the pattern is changed from (\\ d +) to (\\ d)

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

+9
source

I'd be inclined to do something like this

 string testString = new string("test{0}check{1}"); for (int testCount = 0; testCount < 10; testCount++) { for (int checkCount = 0; checkCount < 10; checkCount++) { console.WriteLine(string.FormatString(testString, testCount, checkCount)); } } 

I know that the question has now been answered, but in order to answer the comments, in Java you can do this:

 for (int testCount = 0; testCount < 10; testCount++) { for (int checkCount = 0; checkCount < 10; checkCount++) { String s = String.format("test%scheck%s", testCount.ToString(), checkCount.ToString()); } } 
0
source

All Articles