Java Stringbuilder.replace

Consider the following inputs:

String[] input = {"a9", "aa9", "a9a9", "99a99a"};

What would be the most efficient way to use StringBuilder to replace any digit immediately before the nine with the next letter after it in the alphabet?

After processing these inputs, the output should be:

String[] output = {"b9", "ab9", "b9b9", "99b99a"}

I scratched my head a bit and StringBuilder.setCharAt was the best method I could think of.

Any advice or suggestions would be appreciated.

+5
source share
5 answers

Since you must look at each character, you will never work better than a linearly sized buffer. That way you can just do something like

for (int i=1; buffer.length() ++i) // Note this starts at "1"
    if (buffer.charAt[i] == '9')
        buffer.setCharAt(i-1, buffer.getCharAt(i-1) + 1);
+2
source

You can execute the following code:

String[] input = {"a9", "aa9", "a9a9", "99a99a", "z9", "aZ9"};
String[] output = new String[input.length];
Pattern pt = Pattern.compile("([a-z])(?=9)", Pattern.CASE_INSENSITIVE);
for (int i=0; i<input.length; i++) {
    Matcher mt = pt.matcher(input[i]);
    StringBuffer sb = new StringBuffer();
    while (mt.find()) {
        char ch = mt.group(1).charAt(0);
        if (ch == 'z') ch = 'a';
        else if (ch == 'Z') ch = 'A';
        else ch++;
        mt.appendReplacement(sb, String.valueOf(ch));
    }
    mt.appendTail(sb);
    output[i] = sb.toString();
}
System.out.println(Arrays.toString(output));

CONCLUSION:

[b9, ab9, b9b9, 99b99a, a9, aA9]
+1
source

. , , . 9, boolean true. - , boolean false. .

Reader. a StringBuilder.

0

1 . psuedoish:

for (int index = 0; index < buffer.length(); ++index)
{
  if (index < buffer.length() - 1)
  {
    if (buffer.charAt(index + 1) == '9')
    {
      char current = buffer.charAt(index) + 1; // this is probably not the best technique for this.
      buffer.setCharAt(index, current);
    }
  }
}
0

, ,

StringUtils.indexOf(String str, char searchChar, int startPos) 

, -, ,

0

All Articles