常用方法:
1, char charAt(int index) 获取指定索引位置的char值
public class Test {
public static void main(String args[]) {
String s = "www.runoob.com";
char result = s.charAt(6);
System.out.println(result);
}
}
以上程序执行结果为:
n
2,String concat(String str)将指定字符串连接到改字符串结尾
public class Test {
public static void main(String args[]) {
String s = "菜鸟教程:";
s = s.concat("www.runoob.com");
System.out.println(s);
}
}
以上程序执行结果为:
菜鸟教程:www.runoob.com
3, boolean endsWith(String suffix)测试该字符串是否以指定后缀结尾
4,String toUpperCase()小写转大写
5, String toLowerCase()转小写
6,String substring(int beginIndex)
String substring(int beginIndex, int endIndex)
返回一个新`字符串,它是此字符串的一个子字符串。
public class Test {
public static void main(String args[]) {
String Str = new String("www.runoob.com");
System.out.print("返回值 :" );
System.out.println(Str.substring(4) );
System.out.print("返回值 :" );
System.out.println(Str.substring(4, 10) );
}
}
以上程序执行结果为:
返回值 :runoob.com
返回值 :runoob
7, String[] split(String regex)
String[] split(String regex, int limit)
根据匹配给定的正则表达式来拆分此字符串。
8, char[] toCharArray()
将此字符串转换为一个新的字符数组。
regex – 匹配此字符串的正则表达式。
newChar – 用来替换每个匹配项的字符串。
public class Test {
public static void main(String args[]) {
String Str = new String("www.google.com");
System.out.print("匹配成功返回值 :" );
System.out.println(Str.replaceAll("(.*)google(.*)", "runoob" ));
System.out.print("匹配失败返回值 :" );
System.out.println(Str.replaceAll("(.*)taobao(.*)", "runoob" ));
}
}
以上程序执行结果为:
匹配成功返回值 :runoob
匹配失败返回值 :www.google.com
9, int indexOf(String str, int fromIndex)
返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。
10, int compareTo(Object o)
把这个字符串和另一个对象比较。
public class Test {
public static void main(String args[]) {
String str1 = "Strings";
String str2 = "Strings";
String str3 = "Strings123";
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
result = str3.compareTo( str1 );
System.out.println(result);
}
}
以上程序执行结果为:
0
-3
3