解析字符串的有效方法

时间:2011-05-10 12:31:01

标签: java string substring

比如说你有一个字符串,它有键值,但变量之后的变量 例如:

KEY1=variable1, KEY2=variable2, KEY3=variable3

我想知道的是提取variable1,variable2和variable3的最佳方法是什么。如果我知道子串并且每次都得到它们会很好,但我不知道变量可以改变。请注意,键不会更改

4 个答案:

答案 0 :(得分:5)

你可以试试这个:

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
}

答案 1 :(得分:2)

哈利解决方案的一个变体,它将处理周围的空间,而值=。

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}

答案 2 :(得分:2)

如果你想要超级高效,没有不必要的对象创建,或逐个字符迭代,你可以使用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;
  }
}

答案 3 :(得分:1)

如果您的变量值不能包含逗号或空格,则可以使用“,”将字符串拆分为数组,作为拆分标记。然后,您可以进一步拆分等号上的每个键,以检索键和值。