Unless you can't use apache.commons.lang The code below does not come into play.
Use the strip method. It's fast.
From this point onward, it is recommended only for those who like things.
For example. I want to get elements other than full-width spaces, half-width spaces, and tab characters.
I think it's common. ReplaceAll? "I don't want to replace half-width spaces in the elements I want to retrieve." So I can't use it.
At that time, I wrote the following code. I hope it helps the copy programmer.
private String trim(String target) {
if (target == null || target.isEmpty() || TRIM_CHARS.isEmpty()) {
return target;
}
final char[] chars = target.toCharArray();
int trimHeadIndex = 0;
int trimTailIndex = 0;
for (int i = 0; i < chars.length; i++) {
if (!TRIM_CHARS.contains(chars[i])) {
trimHeadIndex = i;
break;
}
}
for (int t = chars.length; t > 0; t--) {
if (!TRIM_CHARS.contains(chars[t - 1])) {
trimTailIndex = t;
break;
}
}
return target.substring(trimHeadIndex, trimTailIndex);
}
Although TRIM_CHARS is an array
For ease of addition, first with List,
After finishing the operation, set it to Collections # unmodifiableList
and set it to`
It may be better to have it as a constant.
(Not just the final modifier)
I thought again, "I think I can do it with regular expressions." Is it okay because it has been realized?
By the way, even if I experimented with surrogate pair characters, it worked as expected. (Unexpected)
Recommended Posts