1. 程式人生 > >Java中String的用法--部落格園

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(",", "");

 

來源:部落格園https://www.cnblogs.com/hey-man/p/6833242.html