一直应该要总结的String类的方法,废话不说了,直入主题吧:
1、concat(String str)方法是将指定字符串连接到词字符串的结尾,返回的是个string类型。
public class Test {
public static void main(String args[]){
String s = new String("aasssd");
String s1 = "aasd";
s = s.concat(s1);
System.out.println(s);
}
}
运行结果:
aasssdaasd
2、copyValueOf(char[] data)方法是将字符数组转换为String类型返回,有同样作用的还有String类的构造器:String(char[] value)。
public class Test {
public static void main(String args[]){
char[] c = {'d','s','s','f','g'};
String s = String.copyValueOf(c);
System.out.println(s);
}
}
结果为:
dssfg
3、String类型的比较:
equals(Object anObject)将此字符串与指定的对象比较,返回boolean值,将此字符串与指定的对象比较。当且仅当该参数不为 null,并且是与此对象表示相同字符序列的 String 对象时,结果才为 true。同样可进行字符串比较的方法还有compareTo(String), equalsIgnoreCase(String)。
public int compareTo(String anotherString)是按字典顺序比较两字符串,在equals(Object anObject)方法返回true的情况下返回0。
equalsIgnareCase(String)则是在equals(Object anObject)方法的基础上不考虑大小写。
4、String类转为byte[ ] 、char[ ]类型的方法有public byte[] getBytes()、public char[] toCharArray();复制到目标字符数组的指定索引位置的方法还有:
public void getChars(int srcBegin,int srcEnd,char[] dst,int dstBegin),这个方法中,要复制的第一个字符位于索引 srcBegin 处;要复制的最后一个字符位于索引 srcEnd-1 处,要复制到 dst 子数组的字符从索引 dstBegin 处开始。
public class Test {
public static void main(String args[]){
char[] c = {'d','s','s','s'};
String s = "aaaa";
s.getChars(0, 2, c, 1);
System.out.println(c);
}
}
运行结果:
daas
但是结束位置的索引:dstbegin + (srcEnd-srcBegin) - 1要小于目标字符数组的 长度,如果上例中改为
s.getChars(0, 2, c, 3);
则会抛出IndexOutOfBoundsException 异常。
5、 查找指定字符串在字符串中第一次或最后一个出现的位置:
第一次:indexOf(String str);:返回的是str第一次在字符串中出现的位置,若没有检索到,则返回-1
第一次:indexOf(String str,int ,int fromIndex);:从第fronIndex个字符开始检索并返回第一次出现的位置。
最后一次:lastIndexOf(String str);:同上,不过查找的是str在字符串中最后出现的位置。
最后一次:lastIndexOf(String str,int fromIndex);:从fromIndex开始检索。
而如果只是想知道在字符串中是否包含str,而不需要返回它的具体位置,则还有一种方法应该优先考虑:boolean contains(CharSequence s),返回值为FALSE或者 TRUE。
6、测试两个字符串区域是否相等的方法
public boolean regionMatches(int toffset, String other, int ooffset, int len),简单例子如下:
public class Test {
public static void main(String args[]){
String s1 = "aaaa";
String s2 = "bbbaaab";
boolean b = s1.regionMatches(0, s2, 3, 3);
System.out.println(b);
}
}
结果为:
true
7、public Strin[] split (String regex)根据给定正则表达式的匹配拆分字符串的方法:
public class Test {
public static void main(String args[]){
String s = "aa|bb;cc|dd;ee|ff";
String[] c= s.split(";");
for(int i=0; i<c.length; i++){
System.out.println(c[i]);
}
}
}
运行结果:
aa|bb
cc|dd
ee|ff
8、其他还有如截取字符串的方法:
public String substring(int beginIndex,int endIndex);将字符、字符数组或者布尔值等转为字符串的方法:valueOf(char c) 、valueOf(char[] data) 、valueOf(boolean b);转换大小写的方法:toUpperCase()、toLowerCase()在此就不一一赘述了。
最后,为什么我一发博客就格式全乱了,真的调整不清楚了~~先这样吧~等摸索清楚再来改~~~~请见谅啦~~~