解析字符串的有效方法

发布于 2024-11-06 00:59:23 字数 197 浏览 2 评论 0原文

举例来说,您有一个具有键值的字符串,但它后面的变量可以更改 例如:

KEY1=variable1, KEY2=variable2, KEY3=variable3

我想知道提取变量 1、变量 2 和变量 3 的最佳方法是什么。如果我知道子字符串并每次都获取它们,那就太好了,但我不知道变量可以改变。注意按键不会改变

say for example you have a string that has key values but the variables after it can change
ex:

KEY1=variable1, KEY2=variable2, KEY3=variable3

What I want to know is what is the best way to extract variable1, variable2, and variable3. It would be nice if I knew the the substrings and got them each time, but I don't bc the variables can change. Note the keys do not change

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

瞳孔里扚悲伤 2024-11-13 00:59:23

你可以试试这个:

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
}

You can try this:

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
}
Saygoodbye 2024-11-13 00:59:23

Harry 解决方案的一个变体是处理值中 , 和 = 周围的空间。

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}

A variation on Harry's solution which would handle space around the , and = in the value is.

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);

prints

{KEY1=variable1, KEY2=variable2, KEY3=variable3, a=b=1, c=null}
空城缀染半城烟沙 2024-11-13 00:59:23

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

If you want to be super-efficient, no unnecessary object creation, or character by character iteration, you can use indexOf which is more efficient than character by character looping for large substrings.

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;
  }
}
冷月断魂刀 2024-11-13 00:59:23

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

If you're variable values cannot contain commas or spaces, you could simply split the string into an array using the ", " as the split token. Then you could further split each key on the equal sign to retrieve both the key and the value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文