3.1 字符串创建

image.png

3.2 字符串比较 compareTo、compareToIgnoreCase

  1. public class StringCompareEmp{
  2. public static void main(String args[]){
  3. String str = "Hello World";
  4. String anotherString = "hello world";
  5. Object objStr = str;
  6. System.out.println( str.compareTo(anotherString) ); // -32
  7. System.out.println( str.compareToIgnoreCase(anotherString) ); //忽略大小写, 0
  8. System.out.println( str.compareTo(objStr.toString())); // 0
  9. }
  10. }

3.3 字符串替换 replace、replaceFirst、replaceAll

  1. public class StringReplaceEmp{
  2. public static void main(String args[]){
  3. String str="Hello World";
  4. System.out.println( str.replace( 'H','W' ) ); // Wello World
  5. System.out.println( str.replaceFirst("He", "Wa") ); // Wallo World
  6. System.out.println( str.replaceAll("He", "Ha") ); // Hallo World
  7. }
  8. }

3.4 字符串反转 StringBuffer.reverse

  1. String string="runoob";
  2. String reverse = new StringBuffer(string).reverse().toString();

3.5 比较字符串区域相等 regionMatches

  1. public class StringRegionMatch{
  2. public static void main(String[] args){
  3. String first_str = "Welcome to Microsoft";
  4. String second_str = "I work with microsoft";
  5. boolean match1 = first_str.
  6. regionMatches(11, second_str, 12, 9);
  7. boolean match2 = first_str.
  8. regionMatches(true, 11, second_str, 12, 9); //第一个参数 true 表示忽略大小写区别
  9. System.out.println("区分大小写返回值:" + match1); // false Microsoft microsoft
  10. System.out.println("不区分大小写返回值:" + match2); // true
  11. }
  12. }

3.6 字符串格式化 format、printf

  1. public class StringFormat {
  2. public static void main(String[] args){
  3. double e = Math.E;
  4. System.out.format("%f%n", e); // 2.718282
  5. System.out.format(Locale.CHINA , "%-10.4f%n%n", e); // 2.7183, 指定本地为中国(CHINA)
  6. System.out.printf("浮点型变量的值为 " +
  7. "%f, 整型变量的值为 " +
  8. " %d, 字符串变量的值为 " +
  9. "is %s", floatVar, intVar, stringVar);
  10. }
  11. }

3.7 字符串删除 delete

  1. class Test{
  2. public static void main(String[] args){
  3. StringBuffer a = new StringBuffer("Runoob");
  4. StringBuffer b = new StringBuffer("Google");
  5. a.delete(1,3); // delete(x, y) 删除从字符串 x 的索引位置开始到 y-1 的位置
  6. a.append(b);
  7. System.out.println(a); // RoobGoogle
  8. }
  9. }

3.8 字符串连接 concat、+

  1. "Hello," + " runoob" + "!"; // "Hello, runoob!"
  2. "我的名字是 ".concat("Runoob"); // 我的名字是Runoob