1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59 | package Torello.Java;
import Torello.Java.Function.IntCharFunction;
class CharArrToStrReplFunc
{
static String replace(
final boolean ignoreCase,
final String s,
final char[] matchCharsInput,
final IntCharFunction<String> replaceFunction
)
{
// Use a StringBuilder. It is easier since the 'Replace Function' is going to be
// *GENERATING* a new String each and every time there is a match. This is essentially
// what class StringBuilder was deigned for.
StringBuilder sb = new StringBuilder();
// If the case of the characters is being ignored, it is easier to just set them all
// to lower-case right now.
final char[] matchChars;
if (ignoreCase)
{
matchChars = new char[matchCharsInput.length]; // matchCharsInput.clone();
for (int i=0; i < matchChars.length; i++)
matchChars[i] = Character.toLowerCase(matchCharsInput[i]);
}
else matchChars = matchCharsInput;
// IMPORTANT: This entire method is "The Easy Way" Here, we are just reusing Java's
// StringBuilder class to build the String, piece-by-piece. It is
// unknown whether this is less efficient than working with a char[] array
TOP:
for (int i=0; i < s.length(); i++)
{
char c = ignoreCase ? Character.toLowerCase(s.charAt(i)) : s.charAt(i);
for (int j=0; j < matchChars.length; j++)
if (c == matchChars[j])
{
sb.append(replaceFunction.apply(i, c));
continue TOP;
}
sb.append(s.charAt(i));
}
return sb.toString();
}
}
|