下面的代码将字符串拆分为\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,但 的内容分割与之前相同。为什么在正则表达式表达式变化时计算长度差异? :
这里的问题是为什么字符串数组长度值显示1时,它能够成功地分割内容? –
没有分开。您的输出只呈现输入字符串中的换行符。 –
感谢Robby的澄清。 –