下面的代码在 \n
上分割字符串。对于小输入,它确实可以工作,但对于长输入,它不能按相同 \n
的预期工作。
为了调查相同的讨论here 。
编写测试用例来验证行为。
它按 \n
的预期工作,因为当我尝试使用该程序时,答案中有一个建议使用 \\\\n
作为正则表达式进行测试,我得到了不同在字符串数组长度计算中。
下面有代码和我发现的差异。
public String[] token=new String[10];
public Addnumber(String input) {
// TODO Auto-generated constructor stub
this.token=input.split("\n");
System.out.println("Inside constructor Length="+token.length);
for(String s:token)
System.out.println(s);
}
public static void main(String[] args) {
String input="hi\niam\nhere";
String input1="hi\niam\nhere";
String input2="x = [2,0,5,5]\ny = [0,2,4,4]\n\ndraw y #0000ff\ny = y & x\ndraw y #ff0000";
new Addnumber(input1);//calculating via constructor
new Addnumber(input2);
String[] istring=new String[10];
//Calculating in main method
// General expression of \n
istring=input.split("\n");
System.out.println("Length calcluated when \n as regex="+istring.length);
for(String s:istring)
System.out.println(s);
istring=input2.split("\\\\n"); //Check the regex used here
System.out.println("Length calcluated when \\\\n as regex="+istring.length);
for(String s:istring)
System.out.println(s);
}
执行该程序输出如下
Inside constructor Length=3
hi
iam
here
Inside constructor Length=6
x = [2,0,5,5]
y = [0,2,4,4]
draw y #0000ff
y = y & x
draw y #ff0000
Length calcluated when
as regex=3
hi
iam
here
Length calcluated when \\n as regex=1
x = [2,0,5,5]
y = [0,2,4,4]
draw y #0000ff
y = y & x
draw y #ff0000
请注意,当 \n
为正则表达式时,则需要字符串数组的长度,但当 \\\\n
作为正则表达式时,它显示的长度为 1,但
拆分内容与之前相同。为什么正则表达式更改时长度计算会出现差异?
:
最佳答案
我认为你有点忽略了my answer的要点。对于上述问题。
使用 split("\\n")
分割字符串时,您可以通过换行符分割它。
使用 split("\\\\n")
拆分字符串时,您按文字序列 \n
进行拆分。
在 original question ,字符串是通过用户输入得到的,用户按字面输入\n
。因此需要使用\\\\n
来正确拆分。
如果您想模拟文字 \n
用户输入,您的示例字符串需要如下所示:
String input2 = "x = [2,0,5,5]\\ny = [0,2,4,4]\\n\\ndraw y #0000ff\\ny = y & x\\ndraw y #ff0000";
如果您想知道为什么在上一个示例中,它显示长度为 1,但仍将字符串部分呈现在单独的行上:仅呈现输入字符串中的换行符。
关于java - 对于相同输入,使用相同正则表达式的字符串数组长度存在差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29887059/