Java學習之字串類String(一)

2021-07-10 18:39:14 字數 1803 閱讀 5657

public

class stringconparation

}

運算結果

false

true

true

true

運算子==只能檢測是否指向同乙個物件,對於s1和s3指向的物件,和s2不同,而且這裡引入了乙個interned string object的概念,但我現在是覺得沒有必要,你直接說對於兩種不同的建立方法,建立出的物件指向的位址不同就可以了。

比較的話使用equals方法,這裡的返回的boolean型值,還有一種比較的方法就是compareto()方法,這裡返回的就是乙個int型的整數,實際值是根據s1和s2從左到右第乙個不同的字元之間的距離得出的。(距離的計算是否就是ascii嗎呢?結果我的猜想是正確的)

舉例說明compareto()方法:

string s1 = "abc"; 

string s2 = "abcd";

string s3 = "abcdfg";

string s4 = "1bcdfg";

string s5 = "cdfg";

system.out.println( s1.compareto(s2) ); // -1 (前面相等,s1長度小1)

system.out.println( s1.compareto(s3) ); // -3 (前面相等,s1長度小3)

system.out.println( s1.compareto(s4) ); // 48 ("a"的ascii碼是97,"1"的的ascii碼是49,所以返回48)

system.out.println( s1.compareto(s5) ); // -2 ("a"的ascii碼是97,"c"的ascii碼是99,所以返回-2)

+length() :int

//返回這個字串的字元個數

+charat(index:int):char

//返回這個字串的制定下標處的字元

+concat(s1:string):string //返回的這個字串和s1組合而成的新字串

這裡有乙個問題就是如果charat的引數所指的下標是超出這個字串的長度了呢?

解答:這裡會有丟擲乙個異常stringindexoutofbound***ception

+substring(beginindex

:int,endindex

:int)

:string

返回的是以指定的beginindex開始並延續到endindex-1的字串的子串。

+tolowcase():string

+touppercase():string

+trim():string

//返回去掉了兩端的空白字元之後的新字串

+replace(oldchar:char,newchar:char):string

+replacefirst(oldstring:string,newstring:string):string

+replaceall(oldstring:string,newstring:string):string

+split(delimiter:string):string

注釋:repalce方法只能替換乙個字元數,若要用到字串,那只能用repalceall,而repalcefirst只是替換遇到的第乙個字串。(乙個字元數也可以叫字串,只是短一點)

Java系統類之字串類

字串是個常量 不可更改 常量字串 對字串進行操作 都返回是乙個新的字串 原字串不能更改 public static void fun3 public static void fun2 public static void fun1 public static void main string arg...

java字串學習

1,字串 str 中字元的索引從0開始,範圍為 0 到 str.length 1 2.使用 indexof 進行字元或字串查詢時,如果匹配返回位置索引 如果沒有匹配結果,返回 1 3.使用 substring beginindex endindex 進行字串擷取時,包括 beginindex 位置的...

java 溫習之字串(統計字串

統計字串在整個字串中出現的次數 public class stringtest3 這種方法是通過獲得一次後擷取字串 public static int count1 string whole,string son return count 這種方法是通過移動檢索的角標 個人建議用這種,尤其是大篇幅的...