String的常用方法

2021-10-09 04:01:51 字數 3306 閱讀 4055

public string():空構造

public string(byte bytes):把位元組陣列轉成字串

public string(byte bytes,int index,int length):把位元組陣列的一部分轉成字串

public string(char value):把字元陣列轉成字串

public string(char value,int index,int count):把字元陣列的一部分轉成字串,index第一位開始取(包括),count取多少個

public string(string original):把字串常量值轉成字串

length() 返回此字串的長度。

public class test01 ;

//將數字轉換為ascii碼對應的字元值

string s2=new string(bytes);

system.out.println("s2:"+s2);

//擷取字串的一部分

string s3=new string(bytes,0,2);

system.out.println("s3:"+s3);

char chars=;

//將字元陣列轉化為字串

string s4=new string(chars);

system.out.println("s4:"+s4);

string s5=new string(chars,0,2);

system.out.println("s5:"+s5);

string s6=new string("abc");

system.out.println("s6:"+s6);

system.out.println("字串的長度是:"+s6.length());}}

輸出結果:

boolean equals(object obj):比較字串的內容是否相同,區分大小寫

boolean equalsignorecase(string str):比較字串的內容是否相同,忽略大小寫

boolean contains(string str):判斷大字串中是否包含小字串

boolean startswith(string str):判斷字串是否以某個指定的字串開頭

boolean endswith(string str):判斷字串是否以某個指定的字串結尾

boolean isempty():判斷字串是否為空。

//字串的判斷功能

public class test02

}輸出結果:

char charat(int index):獲取指定索引位置的字元

int indexof(int ch):返回指定字元在此字串中第一次出現處的索引

int indexof(string str):返回指定字串在此字串中第一次出現處的索引

int indexof(int ch,int fromindex):返回指定字元在此字串中從指定位置後第一次出現處的索引。

int indexof(string str,int fromindex):返回指定字串在此字串中從指定位置後第一次出現處的索引。

string substring(int start):從指定位置開始擷取字串,預設到末尾。

string substring(int start,int end):從指定位置開始到指定位置結束擷取字串。

//字串的獲取功能

public class test03

}

輸出結果:

byte getbytes():把字串轉換為位元組陣列。

char tochararray():把字串轉換為字元陣列。

static string valueof(char chs):把字元陣列轉成字串。

static string valueof(int i):把int型別的資料轉成字串。

string tolowercase():把字串轉成小寫。

string touppercase():把字串轉成大寫。

string concat(string str):把字串拼接。

//字串的轉換功能

public class test04 ;

system.out.println(string.valueof(c2));

//把int型的資料轉化成字串

string a=string.valueof(123);

system.out.println(a);

//把字串轉化為小寫

string s2="abcd";

system.out.println(s2.tolowercase());

//把字串轉化為大寫

string s3="aaa";

system.out.println(s3.touppercase());

}}輸出結果:

string replace(char old,char new):把字串中的某個字元用新的字元所替換

string replace(string old,string new)把字串中的某個字串用新的來替換

string trim() 去除字串兩空格

//字串的替換功能

public class test05

}

輸出結果:

String的常用方法

1 字元陣列與字串 乙個字串可以變為乙個字元陣列,同樣,也可以把乙個字元陣列,變為乙個字串。在string類中提供了以下的操作方法 將字串變為字元陣列 1.tochararray 返回 char 例 string str 你好 char c str.tochararray 字元陣列變為字串 1.ch...

String常用的方法

no.方法名稱 型別 描述1 public string char value 構造 將全部字元陣列變為字串 2public string char value,int offset,int count 構造 將部分字元陣列變為字串 3public char charat int index 普通 ...

String的常用方法

string的常用方法 public int length 獲取字串當中含有的字元個數,拿到字串長度。public stirng concat string str 將當前字串和引數字串拼接成為返回值新的字串。public char charat int index 獲取指定索引位置的單個字元。索引...