使用内置字符串函数

时间:2016-03-29 12:53:33

标签: java string data-structures

如何转换下面的字符串

String str="[in,us,eu,af,th]";

进入

["in","us","eu","af","th"]

3 个答案:

答案 0 :(得分:4)

只需使用字符串函数:

str = str.substring(1,str.length()-2); // remove brackets
String a[] = str.split(","); //split it.

答案 1 :(得分:0)

public static void main(String[] args) {
    String str = "[in,us,eu,af,th]";

    str = str.substring(1, str.length() - 1);

    // #1 remove starting and ending brackets
    System.out.println("String without brackets : " + str);

    //#2 split by comma
    String[] stringTokens = str.split(",");
    StringBuffer outputStrBuffer = new StringBuffer();

    outputStrBuffer.append("["); // append starting square bracket

    for (int i = 0; i <= stringTokens.length - 1; i++) {
        //prefix and postfix each token with double quote
        outputStrBuffer.append("\"");
        outputStrBuffer.append(stringTokens[i]);
        outputStrBuffer.append("\"");

        // for last toke dont append comma at end
        if (i != stringTokens.length - 1) {
            outputStrBuffer.append(",");
        }
    }
    outputStrBuffer.append("]"); // append ending square bracket

    System.out.println("String prefixed & postfixed with double quotes, separated by comma : " + outputStrBuffer.toString());
}

答案 2 :(得分:0)

String result = str.replace("[", "[\"").replace(",", "\",\"").replace("]", "\"]");