string的用法

一、字符串对象的构造:
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(",", "");