3.1 字符串创建
3.2 字符串比较 compareTo、compareToIgnoreCase
public class StringCompareEmp{
public static void main(String args[]){
String str = "Hello World";
String anotherString = "hello world";
Object objStr = str;
System.out.println( str.compareTo(anotherString) ); // -32
System.out.println( str.compareToIgnoreCase(anotherString) ); //忽略大小写, 0
System.out.println( str.compareTo(objStr.toString())); // 0
}
}
3.3 字符串替换 replace、replaceFirst、replaceAll
public class StringReplaceEmp{
public static void main(String args[]){
String str="Hello World";
System.out.println( str.replace( 'H','W' ) ); // Wello World
System.out.println( str.replaceFirst("He", "Wa") ); // Wallo World
System.out.println( str.replaceAll("He", "Ha") ); // Hallo World
}
}
3.4 字符串反转 StringBuffer.reverse
String string="runoob";
String reverse = new StringBuffer(string).reverse().toString();
3.5 比较字符串区域相等 regionMatches
public class StringRegionMatch{
public static void main(String[] args){
String first_str = "Welcome to Microsoft";
String second_str = "I work with microsoft";
boolean match1 = first_str.
regionMatches(11, second_str, 12, 9);
boolean match2 = first_str.
regionMatches(true, 11, second_str, 12, 9); //第一个参数 true 表示忽略大小写区别
System.out.println("区分大小写返回值:" + match1); // false Microsoft microsoft
System.out.println("不区分大小写返回值:" + match2); // true
}
}
3.6 字符串格式化 format、printf
public class StringFormat {
public static void main(String[] args){
double e = Math.E;
System.out.format("%f%n", e); // 2.718282
System.out.format(Locale.CHINA , "%-10.4f%n%n", e); // 2.7183, 指定本地为中国(CHINA)
System.out.printf("浮点型变量的值为 " +
"%f, 整型变量的值为 " +
" %d, 字符串变量的值为 " +
"is %s", floatVar, intVar, stringVar);
}
}
3.7 字符串删除 delete
class Test{
public static void main(String[] args){
StringBuffer a = new StringBuffer("Runoob");
StringBuffer b = new StringBuffer("Google");
a.delete(1,3); // delete(x, y) 删除从字符串 x 的索引位置开始到 y-1 的位置
a.append(b);
System.out.println(a); // RoobGoogle
}
}
3.8 字符串连接 concat、+
"Hello," + " runoob" + "!"; // "Hello, runoob!"
"我的名字是 ".concat("Runoob"); // 我的名字是Runoob