下面的代碼將字符串拆分爲\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的澄清。 –