tags:

views:

154

answers:

2

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

+3  A: 

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");
StringBuilder result = new StringBuilder();
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.

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

Adrian Pronk
Thanks, that was exactly what i need!
Le_Coeur
A: 

Id 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 the question has now been answered but to address 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()); 
   }
}
Mauro
it's a Java question, not c#.
Omry