【发布时间】:2015-04-27 04:10:06
【问题描述】:
以下代码在\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 但
内容拆分与以前相同。为什么正则表达式更改时长度计算会出现差异?
:
【问题讨论】: