字串拼接理解

2021-08-20 09:24:48 字數 1320 閱讀 1656

string str3="hello"+" word!";  

string str4="hello word!";

system.out.println(str3==str4);

//執行結果:true

原因:jvm編譯器對字串做了優化,在編譯時str3就已經被優化成「hello word!」,str3和str4指向字串常量池同乙個字串常量,所以==比較為true。

double x = 9.987;

double y = 1;

double t = x+y;

string str3="hello"+" word!";

string str4="hello word!";

system.out.println(str3==str4);

string s = "price is:"+x;

string st = "total price is:"+t;

system.out.println(s);

system.out.println(st);

system.out.println(""+x+y);

system.out.println(x+y+"");

//容易產生空指標異常

//student s=new student();

//s=null;

//if((s!=null)&(s.getname().equals("zs")))

////永遠為false

//if((s!=null)&&("zs"==(s.getname()))

//正確寫法

//if((s!=null)&&("zs".equals(s.getname()))

//}

「price is」+ x,會建立兩個string型別的物件,一開始先在方法區的常量池裡建立「prince is」,然後由於有乙個「+」號,會馬上把x這個9.987轉換成string,又在方法區的常量池,string物件的屬性是final。接著又在常量池建立乙個string物件:price is9.987。

string物件的建立物件的方式:一、new乙個;二、string a = 「123456」;三、用+號

結果:

可以看出,string型別的物件後面跟著「+」,不管後面為什麼變數,都會轉化成string型別的字串,然後把他們做鏈結,所以會有結果9.9871.0。

拼接字串

border 1 class box 標籤名稱th 是否顯示th 標籤順序th tr thead 首頁td class check 是option 否option select td class number 1option 2option 3option 4option 5option 6opti...

字串拼接

給定兩個字串s1和s2,合併成乙個新的字串s。合併規則為,s1的第乙個字元為s的第乙個字元,將s2的最後乙個字元作為s的第二個字元 將s1的第二個字元作為s的第三個字元,將s2的倒數第二個字元作為s的第四個字元,以此類推。包含多組測試資料,每組測試資料報含兩行,代表長度相等的兩個字串s1和s2 僅由...

字串拼接

本文總結記錄linux c中有關字串的拼接方法,strncat 和 snprintf 函式 一 strncat 實現字串拼接 char strncat char dest,const char src,size t n 宣告,n 為 src 字串長度 char strncat char dest,c...