-2

我有一个字符串

str=123|apple|apple|apple|dog$

我喜欢用“|”分隔字符串 特点。

    String str = "123|apple|apple|apple|dog$";
    StringTokenizer strString = new StringTokenizer(str..nextToken(), "|");
    int i;
    while (strString.hasMoreElements()) {
        if (i == 0)
            str1 = Loginstring.nextToken();
        else if (i == 1)
            str2 = Integer.Loginstring.nextToken();
        else if (i == 2) {
            str3 = Loginstring.nextToken();
            break;
        }
        i = i + 1;
    }

但它在第一个循环开始时退出(这意味着如果我超过 1 则它从循环中退出),我真的不知道它发生了什么,它有什么问题

4

2 回答 2

5

这就是您要实现的目标

String str1 = "", str2 = "", str3 = "", str4 = "", str5 = "";
String str = "123|apple|apple|apple|dog$";
StringTokenizer strString = new StringTokenizer(str, "|");
int k = 0;
while (strString.hasMoreElements()) {
    if (k == 0)
        str1 = strString.nextToken();
    else if (k == 1)
        str2 = strString.nextToken();
    else if (k == 2) {
        str3 = strString.nextToken();
    } else if (k == 3) {
        str4 = strString.nextToken();
    } else if (k == 4) {
        str5 = strString.nextToken();
        break;
    }
    k = k + 1;
}
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);

但这可以很容易地在一个语句中完成

String[] tokens = str.split("\\|"); // this is that single statment
for (String token : tokens)
    System.out.println(token);

str1 = tokens[0];
str2 = tokens[1];
str3 = tokens[2];
str4 = tokens[3];
str5 = tokens[4];

System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);
System.out.println(str5);
于 2012-07-19T12:24:49.133 回答
1

用于String.split("\\|")分割字符串。

于 2012-07-19T12:10:38.780 回答