Java中String的用法


這兩天學習用到String的一些用法,於是就總結出了這么幾項,希望對你們有所幫助。
String類用來定義及使用字符串,string類位於java.lang包中,所以不用import就能用Stirng來實例化對象。

一、字符串對象的構造:
1、

String s;
s = new String("We are students");

等價於

String s = "We are students";

String s = new String("We are students");

2、用無參構造方法生成一個空字符串對象

String s = new String();

3、用字符數組構造字符串

char c1[] = {'2','3','4','5'};
String str1 = new String(c);
char c2[] = {'1','2','3','4','5'};
String str2 = new String(c2,1,4);//從第一個字符串開始,長度為4

 

上面兩個構造方法生成的字符串實例的內容均為"2345".

4、用字節數組構造字符串

byte c1[]={66,67,68};
byte c2[]={65,66,67,68};
String str1 = new String(c1);
String str2 = new String(c2,1,3);//從字節數組的第一個字節開始,取3個字節

上面兩個構造的字符串實例內容均為"BCD";
二、字符串的常用方法
1、int length():獲取長度

String s = "We are students";
int len=s.length();

2、char charAt(int index);根據位置獲取位置上某個字符。

String s = "We are students";
char c = s.charAt(14);

3、int indexOf(int ch):返回的是ch在字符串中第一次出現的位置。

String s = "We are students";
int num = s.indexOf("s");

4、int indexOf(int ch,int fromIndex):從fromIndex指定位置開始,獲取ch在字符串中出現的位置。
5、int indexOf(String str):返回的是str在字符串中第一次出現的位置。
6、int indexOf(String str,int fromIndex):從fromIndex指定位置開始,獲取str在字符串中出現的位置。
7、int lastIndexOf(String str):反向索引。
8、boolean contains(str);字符串中是否包含某一個子串
9、boolean isEmpty():原理就是判斷長度是否為0。
10、boolean startsWith(str);字符串是否以指定內容開頭。
11、boolean endsWith(str);字符串是否以指定內容結尾。
12、boolean equals(str);判斷字符內容是否相同
13、boolean.equalsIgnorecase();判斷內容是否相同,並忽略大小寫。
14、String trim();將字符串兩端的多個空格去除
15、int compareTo(string);對兩個字符串進行自然順序的比較
16、String toUpperCsae() 大轉小 String toLowerCsae() 小轉大
17、 String subString(begin); String subString(begin,end);獲取字符串中子串
18、String replace(oldchar,newchar);將字符串指定字符替換。

String s = "123,123,123";
String str = s.replace(",", "");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM