Если вы хотите быть сверхэффективным, без создания ненужных объектов или посимвольной итерации, вы можете использовать indexOf
, который более эффективен, чем посимвольное зацикливание для больших подстрок.
public class ValueFinder {
// For keys A, B, C will be { "A=", ", B=", ", C=" }
private final String[] boundaries;
/**
* @param keyNames To parse strings like {@code "FOO=bar, BAZ=boo"}, pass in
* the unchanging key names here, <code>{ "FOO", "BAZ" }</code> in the
* example above.
*/
public ValueFinder(String... keyNames) {
this.boundaries = new String[keyNames.length];
for (int i = 0; i < boundaries.length; ++i) {
boundaries[i] = (i != 0 ? ", " : "") + keyNames[i] + "=";
}
}
/**
* Given {@code "FOO=bar, BAZ=boo"} produces <code>{ "bar", "boo" }</code>
* assuming the ctor was passed the key names <code>{ "FOO", "BAZ" }</code>.
* Behavior is undefined if {@code s} does not contain all the key names in
* order.
*/
public String[] parseValues(String s) {
int n = boundaries.length;
String[] values = new String[n];
if (n != 0) {
// The start of the next value through the loop.
int pos = boundaries[0].length();
for (int i = 0; i < n; ++i) {
int start = pos;
int end;
// The value ends at the start of the next boundary if
// there is one, or the end of input otherwise.
if (i + 1 != n) {
String next = boundaries[i + 1];
end = s.indexOf(next, pos);
pos = end + next.length();
} else {
end = s.length();
}
values[i] = s.substring(start, end);
}
}
return values;
}
}