2011-05-10 88 views
4

比方说你有一个具有关键值,但这些变量后,它可以改变 前的字符串:有效的方式来解析字符串

KEY1=variable1, KEY2=variable2, KEY3=variable3 

我想知道的是什么,是提取变量1的最佳方式,变量2和变量3。如果我知道每个子字符串,并且每次都得到它,那将会很好,但是我不会改变这些变量。请注意,密钥不会更改

+0

http://stackoverflow.com/questions/5887559/best-way-to-retrieve-a-value-from-a-string-java/5887890#5887890的可能的复制 – 2011-05-10 12:38:35

回答

1

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

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 
} 
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

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