简体   繁体   English

使用split()方法输出错误?

[英]Error in output using split() method?

I am trying to use simple split() method but the output I am getting is not Correct .I am using this code: 我试图使用简单的split()方法,但我得到的输出不正确。我使用此代码:

        question = newobject.ACTIVITY_LIST_OF_QUESTIONS.split("|");

where the newobject.ACTIVITY_LIST_OF_QUESTIONS contains 1|2|8|11|4|5|6|14|15|16|13|17|7|9|12|10 as a String so I must be getting each number in array index. 其中newobject.ACTIVITY_LIST_OF_QUESTIONS包含1 | 2 | 8 | 11 | 4 | 5 | 6 | 14 | 15 | 16 | 13 | 17 | 7 | 9 | 12 | 10作为字符串所以我必须得到数组索引中的每个数字。

But instead of that I am getting output- 但是,而不是我得到输出 -

       1
       |
       2
       |
       8

Please help If someone had the same problem? 请帮助如果有人遇到同样的问题?

You should use split("\\\\|") . 你应该使用split("\\\\|") You need to break the special meaning of the regex | 你需要打破的特殊含义正则表达式 | . You do so with \\\\| 你可以用\\\\| . [Note that split() is splitting according to regex]. [注意, split()根据正则表达式进行拆分]。

String s = "1|2|8|11|4|5|6|14|15|16|13|17|7|9|12|10";
String[] arr = s.split("\\|");
System.out.println(Arrays.toString(arr));

results in: 结果是:

[1, 2, 8, 11, 4, 5, 6, 14, 15, 16, 13, 17, 7, 9, 12, 10]

You need to escape | 你需要逃避| as \\\\| 作为\\\\| . Your regex is being interpreted as "empty string or empty string", so each position matches. 您的正则表达式被解释为“空字符串or空字符串”,因此每个位置都匹配。

A | A | is a regex metacharacter used to denote alteration. 是一个正则表达式元字符,用于表示更改。 To mean a literal | 表示文字| you need to escape it as \\\\| 你需要以\\\\|来逃避它 or put it in a character class [|] . 或者把它放在一个字符类[|]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM