测试String类里的方法
代码:
public static void main(String[] args) {
String str1 = new String("abcdE");
String str2 = new String("12345");
System.out.println(str1.charAt(1));//返回指定索引处的 char 值。
System.out.println(str1.compareTo(str2));// 按字典顺序比较两个字符串。
System.out.println(str1.concat(str2));// 将指定字符串连接到此字符串的结尾。
System.out.println(str1.contains("a"));// 当且仅当此字符串包含指定的 char 值序列时,返回 true。
System.out.println(str1.indexOf("a"));// 返回指定字符在此字符串中第一次出现处的索引。
System.out.println(str1.contains("ab"));// 返回指定子字符串在此字符串中第一次出现处的索引。
System.out.println(str1.intern());// 返回字符串对象的规范化表示形式。
System.out.println(str1.isEmpty() );// 当且仅当 length() 为 0 时返回 true。
System.out.println(str1.lastIndexOf("b"));// 返回指定字符在此字符串中最后一次出现处的索引。
System.out.println(str1.length());// 返回此字符串的长度。
System.out.println(str1.replace("a","d"));// 返回一个新的字符串,它是通过用 newChar 替换此字符串中出现的所有 oldChar 得到的。
System.out.println(str1.startsWith("a"));// 测试此字符串是否以指定的前缀开始。
System.out.println(str1.substring(1,3));// 返回一个新字符串,它是此字符串的一个子字符串。
System.out.println(str1.toCharArray());// 将此字符串转换为一个新的字符数组。
System.out.println(str1.toLowerCase());// 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
System.out.println(str1.toUpperCase());// 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
}
}
结果:
StringBuffer类里的方法
代码:
public class Test {
public static void main(String[] args) {
StringBuffer strb1 = new StringBuffer("abcdE");
StringBuffer strb2 = new StringBuffer("qwer");
System.out.println( strb1.indexOf("cd"));// 返回子字符串在字符串中最先出现的位置,如果不存在,返回负数
System.out.println( strb1.substring(1,3));// substring方法截取字符串,可以指定截取的起始位置和终止位置
System.out.println( strb1.substring(1,3));// substring方法截取字符串,可以指定截取的起始位置和终止位置 d
System.out.println( strb1.append(1));// 添加各种类型的数据到字符串的尾部
System.out.println( strb1.append("a"));// 添加各种类型的数据到字符串的尾部
System.out.println( strb1.append(1.23f));// 添加各种类型的数据到字符串的尾部
System.out.println( strb1.append(strb2));// 添加各种类型的数据到字符串的尾部
System.out.println( strb1.insert(2, 'W'));// 向字符串中插入各种类型的数据
System.out.println( strb1.replace(1,2,"123e"));// 替换字符串中的某些字符
System.out.println( strb1.reverse());// 将字符串倒序
}
}
结果:
通过上面两题的结果不难发现String 和StringBuffer两个类最大的区别就是字符串是常量;它的值在创建之后不能更改。,对其本身不产生任何的影响,而StringBuffer是在输入的对象上直接操作,所以在要注意这一点,正确的选择String 和StringBuffer。