spilt 和 replaceAll两个方法是String 对正则表达式的支持,在使用时可以使用正则表达式进行复杂匹配。正则表达式的内容在常用类库章节将为读者介绍。
1.字符串与字符数组的转换。
字符串可以使用toCharAyyay()方法 也可以使用String类的构造方法把一个字符数组变为字符串。
public class StringAPIDemo{
public static void main(String[] args){
String str1="hello";
char c[] =str1.toCharArray();
for (int i=0;i<c.length;i++){
System.out.print(c(i)+'\t");
}
System.out.println("");
String str2 =new String(c);
String str3 =new Stringz(c,0,3);
System.out.print(str2);
System.out.print(str3);
}
}
h e l l 0
hello
hel
1.从字符串中取出指定位置的字符 charAt() str1.charAt(3) //取出第4个字符
getByes()方法将String变为一个byte数组
byte b[]=str1.getByes();
byte 与char 数组转换风格相似。
length 取得数组的长度 length()取得字符串的长度 字符串调用length()是一个方法,只要是方法后面都有()
2。indexOf()方法可以返回指定字符串的位置如果不存在返回-1
str1.indexOf("c") //查到返回位置
str1.indexOf("c",3)//从第四个开始查找
3.去掉左右空格 trim()方法
str1.trim()
4.截取字符串substring
5.按照指定的字符串拆分字符串 split()方法
拆分的数据将以字符串数组的形式返回
public class StringAPIDemo{
public static void main (String[] args){
String str1 ="hello world";
String s[] =str1.split(" "); //按空格进行字符串的拆分
for(int i=0;i<s.length;i++){
System.out.println(s([i]);
}
}
}
hello
world
s.length 为2 s[0]=hello s[1]=world
int a[][] ={{ 1,2,3},{4,5,6}};
a.length=2
a[0].length=3
a[1].length=3
大写:println("hello world".toUpperCase());
小写:println("hello world".toLowerCase());
6.判断字符串以什么开头和结尾
str1.startsWith(“**”);
str1.endsWith("**");
7.不区分大小写进行字符串比较 equals()区别大小写
equalsIgnoreCase()不区分大小写
str1.equalsIgnoreCase(str2);
8.将一个指定的字符串替换成其它字符串
使用String的replaceAll()方法可以将字符串的指定内容替换
String newstr=str.replaceAll("l","x")
hexxo
5.8引用传递及基本应用