基礎類庫 String類 Part2

2021-07-23 15:26:29 字數 2975 閱讀 4093

3.成員方法

a.判斷功能

a.boolean equals(object anobject) 區分大小寫

object類的equals方法比較的是位址值;被string類重寫的equals方法比較的是字串的內容

字串行相同,則true,否則為false

b.boolean equalsignorecase(string anotherstring) 不區分大小寫

將此 string 與另乙個 string 比較,不考慮大小寫。

c.boolean contains(string s)

大串是否包含小串

d.boolean startswith(string prefix)

測試此字串是否以指定的字首開始。

e.boolean endswith(string s)

測試此字串是否以指定的字尾結束。

f.boolean isempty()

是否是空字串

b.獲取功能

a. char charat(int index)

返回指定索引處的 char 值。

b.int indexof(int ch) 找不到,不存在都是-1

返回指定字元在此字串中第一次出現處的索引。

c.int indexof(string str)

返回指定子字串在此字串中第一次出現處的索引。

d. int indexof(string str, int fromindex)

返回指定子字串在此字串中第一次出現處的索引,從指定的索引開始。

e.string substring(int beginindex)

返回乙個新的字串,它是此字串的乙個子字串。

f.string substring(int beginindex, int endindex)

返回乙個新字串,它是此字串的乙個子字串。

c.轉換功能

a.byte getbytes(string charsetname) 把字串轉換成位元組陣列

b.char tochararray() 把字串轉換成字元陣列

c.static string valueof(char data) 把字元陣列轉換成字串

d.static string valueof(int i) 把int轉換成字串,另外還有其他基本型別

e.string tolowercase() 所有字元都轉換為小寫

f.string touppercase() 所有字元都轉換為大寫

g.string concat(string str) 將指定字串連線到此字串的結尾。

注意:string類的靜態方法可以將任意型別的資料轉換成字串

static string valueof(基本型別 value);基本型別

static string valueof(object obj);引用型別

d.其他功能

a.替換

string replace(char oldchar, char newchar)

返回乙個新的字串,它是通過用 newchar 替換此字串中出現的所有 oldchar 得到的。

string replace(string old,string new)

用新的字串,替代原字串的某一子串

b.去除字串首尾空格

string trim()

返回字串的副本,忽略前導空白和尾部空白

c.按字典順序比較兩個字串

int compareto(string anotherstring) 按字典順序比較兩個字串。

int comparetoignorecase(string str) 按字典順序比較兩個字串,不考慮大小寫。

package api_ordinary;

public

class stringdemo2

system.out.println("\n大寫字母個數:"+big+"\n小寫字母個數:"+small+"\n數字個數:"+num);

//替換功能

//string replace(char oldchar, char newchar)

s="aaaabbbcccddd";

system.out.println(s.replace('a', 'i'));

//string replace(string old,string new)

system.out.println(s.replace("aa", "***xx"));

//去除字串首尾空格,中間的空格去不掉

s=" abcd ";

system.out.println(s.trim());

//按字典順序比較兩字串

s1="hello";

s2="hello";

s3="abc";

string s4="xyz";

system.out.println(s1.compareto(s2));//都相同,則為0

system.out.println(s1.compareto(s3));//index處不同,則s1的index處字元的ascii值減s2處的

system.out.println(s1.compareto(s4));

}}

true

true

true

true

true

true

n 1

6 6

20 america

am helloiamkangkangfromamerica

大寫字母個數:3

小寫字母個數:6

數字個數:3

iiiibbbcccddd

*********xbbbcccddd

abcd

0 7

-16

C 基礎 string類和標準模板庫

智慧型指標模板類 標準模板庫 泛型程式設計 函式物件 演算法其他庫 內容包括 標準c string類 模板auto ptr unique ptr和shared ptr 標準模板庫 stl 容器類 迭代器 函式物件 stl演算法 模板initializer list string類的建構函式 建構函式...

java基礎 String類命令

1 regionmatches方法 regionmatches方法用於檢測兩個字串在乙個區域內是否相等 public boolean regionmatches int toffset,string other,it ooffset,int len public boolean regionmatc...

Java 基礎之String類

1.string類初始化方法 public class main string str3 new string chars string str4 new string chars,1,4 system.out.println str1 str1 system.out.println str2 st...