下面的代码在\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,但拆分的内容与以前相同。 regex表达式更改时,为什么长度计算有差异?
:
最佳答案
我认为您在某种程度上错过了上述问题的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,但仍将字符串部分呈现在单独的行中:只是呈现输入字符串中的换行符。