[英]Efficient way to Parse String
例如,你有一個字符串,其中包含鍵值,但變量后面的變量可以更改ex:
KEY1=variable1, KEY2=variable2, KEY3=variable3
我想知道的是提取variable1,variable2和variable3的最佳方法是什么。 如果我知道子串並且每次都得到它們會很好,但我不知道變量可以改變。 請注意,鍵不會更改
你可以試試這個:
String str = "KEY1=variable1, KEY2=variable2, KEY3=variable3";
String[] strArr = str.split(",");
String[] strArr2;
for (String string : strArr) {
System.out.println(string); // ---- prints key-value pair
strArr2 = string.trim().split("=");
System.out.println(strArr2[1]); // ---- prints value
}
哈利解決方案的一個變種,它將處理周圍的空間,並且=在值中。
String str = "KEY1=variable1, KEY2=variable2, KEY3=variable3 , a = b=1, c";
Map<String, String> map = new LinkedHashMap<String, String>();
for (String string : str.trim().split(" *, *")) {
String[] pair = string.split(" *= *", 2);
map.put(pair[0], pair.length == 1 ? null : pair[1]);
}
System.out.println(map);
版畫
{KEY1=variable1, KEY2=variable2, KEY3=variable3, a=b=1, c=null}
如果你想要超高效,沒有不必要的對象創建,或者逐字符迭代,你可以使用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;
}
}
如果您的變量值不能包含逗號或空格,則可以使用“,”作為拆分標記將字符串拆分為數組。 然后,您可以進一步拆分等號上的每個鍵,以檢索鍵和值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.