程序资料 March 20, 2021

Java实例之字符串

Words count 11k Reading time 10 mins. Read count 0

1. 字符串比较

  • 调用String类的.compareTo(string), .compareToIgnoreCase(string)``, compareTo(object string),返回第一个字母的ASCII差值。

    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) );//  print -32
        System.out.println( str.compareToIgnoreCase(anotherString) );  //忽略大小写 print 0
        System.out.println( str.compareTo(objStr.toString()));// print 0
     }
    }

2. 查找字符串最后一次出现的位置

  • 通过调用String类的 str.lastIndexOf(' '),返回第一次出现该字段的索引值。
    public class SearchlastString {
     public static void main(String[] args) {
        String strOrig = "Hello world ,Hello Runoob";
        int lastIndex = strOrig.lastIndexOf("Runoob");
        if(lastIndex == - 1){
           System.out.println("没有找到字符串 Runoob");
        }else{
           System.out.println("Runoob 字符串最后出现的位置: "+ lastIndex);
        }
     }
    }

3. 删除字符串中的一个字符

  • 通过两次调用String类的str.substring(pos1,pos2)来实现字符串的截取。
    public class Main {
     public static void main(String args[]) {
        String str = "this is Java";
        System.out.println(removeCharAt(str, 3));
     }
     public static String removeCharAt(String s, int pos) {
        return s.substring(0, pos) + s.substring(pos + 1);
     }
    }

4. 字符串替换

  • 通过调用String类的indexOf()的str.replace()来对字符串进行替换。
    public class StringReplaceEmp{
     public static void main(String args[]){
        String str="Hello World";
        System.out.println( str.replace( 'H','W' ) );
        System.out.println( str.replaceFirst("He", "Wa") );
        System.out.println( str.replaceAll("He", "Ha") );
     }
    }

5.字符串反转

public class StringReverseExample{
   public static void main(String[] args){
      String string="runoob";
      String reverse = new StringBuffer(string).reverse().toString();
      System.out.println("字符串反转前:"+string);
      System.out.println("字符串反转后:"+reverse);
   }
}

6. 字符串搜索

  • 通过调用String类的str.indexOf(' '),查找出现该字段的位置,返回第一个字母的索引值,返回值为-1则查找失败。
    public class SearchStringEmp {
     public static void main(String[] args) {
        String strOrig = "Google Runoob Taobao";
        int intIndex = strOrig.indexOf("Runoob");
        if(intIndex == - 1){
           System.out.println("没有找到字符串 Runoob");
        }else{
           System.out.println("Runoob 字符串位置 " + intIndex);
        }
     }
    }

7. 字符串分割

public class JavaStringSplitEmp {
   public static void main(String args[]){

      String str = "www-runoob-com";
      String[] temp;
      String delimeter = "-";  // 指定分割字符
      temp = str.split(delimeter); // 分割字符串
      // 普通 for 循环
      for(int i =0; i < temp.length ; i++){
         System.out.println(temp[i]);
         System.out.println("");
      }

      System.out.println("------java for each循环输出的方法-----");
      String str1 = "www.runoob.com";
      String[] temp1;
      String delimeter1 = "\\.";  // 指定分割字符, . 号需要转义
      temp1 = str1.split(delimeter1); // 分割字符串
      for(String x :  temp1){
         System.out.println(x);
         System.out.println("");
      }
   }
}

8. 字符串分割

  • 调用String类的str.split()方法,返回值存储在String[]中。

    public class JavaStringSplitEmp {
     public static void main(String args[]){
    
        String str = "www-runoob-com";
        String[] temp;
        String delimeter = "-";  // 指定分割字符
        temp = str.split(delimeter); // 分割字符串
        // 普通 for 循环
        for(int i =0; i < temp.length ; i++){
           System.out.println(temp[i]);
           System.out.println("");
        }
    
        System.out.println("------java for each循环输出的方法-----");
        String str1 = "www.runoob.com";
        String[] temp1;
        String delimeter1 = "\\.";  // 指定分割字符, . 号需要转义
        temp1 = str1.split(delimeter1); // 分割字符串
        for(String x :  temp1){
           System.out.println(x);
           System.out.println("");
        }
     }
    }

    9. 字符串大写转小写

  • String类的str.toUpperCase();

    public class StringToUpperCaseEmp {
      public static void main(String[] args) {
          String str = "string runoob";
          String strUpper = str.toUpperCase();
          System.out.println("原始字符串: " + str);
          System.out.println("转换为大写: " + strUpper);
      }
    }

10. 测试两个字符串区域是否相等

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);
      System.out.println("不区分大小写返回值:" + match2);
   }
}

11. 字符串性能比较测试

public class StringComparePerformance{
   public static void main(String[] args){      
      long startTime = System.currentTimeMillis();
      for(int i=0;i<50000;i++){
         String s1 = "hello";
         String s2 = "hello";
      }
      long endTime = System.currentTimeMillis();
      System.out.println("通过 String 关键词创建字符串" 
      + " : "+ (endTime - startTime) 
      + " 毫秒" );       
      long startTime1 = System.currentTimeMillis();
      for(int i=0;i<50000;i++){
         String s3 = new String("hello");
         String s4 = new String("hello");
      }
      long endTime1 = System.currentTimeMillis();
      System.out.println("通过 String 对象创建字符串" 
      + " : " + (endTime1 - startTime1)
      + " 毫秒");
   }
}

12. 字符串优化

public class StringOptimization {
    public static void main(String[] args){
        String variables[] = new String[50000];      
        for( int i=0;i <50000;i++){
            variables[i] = "s"+i;
        }
        long startTime0 = System.currentTimeMillis();
        for(int i=0;i<50000;i++){
            variables[i] = "hello";
        }
        long endTime0 = System.currentTimeMillis();
        System.out.println("直接使用字符串: "+ (endTime0 - startTime0)  + " ms" );
        long startTime1 = System.currentTimeMillis();
            for(int i=0;i<50000;i++){
            variables[i] = new String("hello");
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("使用 new 关键字:" + (endTime1 - startTime1) + " ms");
        long startTime2 = System.currentTimeMillis();
        for(int i=0;i<50000;i++){
            variables[i] = new String("hello");
            variables[i] = variables[i].intern();          
        }
        long endTime2 = System.currentTimeMillis();
        System.out.println("使用字符串对象的 intern() 方法: " 
        + (endTime2 - startTime2)
        + " ms");
    }
}

13. 字符串格式化

import java.util.*;

public class StringFormat {
    public static void main(String[] args){
        double e = Math.E;
        System.out.format("%f%n", e);
        System.out.format(Locale.CHINA  , "%-10.4f%n%n", e);  //指定本地为中国(CHINA)
    }
}

14.连接字符串

public class StringConcatenate {
    public static void main(String[] args){
        long startTime = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            String result = "This is"
            + "testing the"
            + "difference"+ "between"
            + "String"+ "and"+ "StringBuffer";
        }
        long endTime = System.currentTimeMillis();
        System.out.println("字符串连接" 
        + " - 使用 + 操作符 : " 
        + (endTime - startTime)+ " ms");
        long startTime1 = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            StringBuffer result = new StringBuffer();
            result.append("This is");
            result.append("testing the");
            result.append("difference");
            result.append("between");
            result.append("String");
            result.append("and");
            result.append("StringBuffer");
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("字符串连接" 
        + " - 使用 StringBuffer : "
        + (endTime1 - startTime1)+ " ms");
    }
}
  • String.format() 创建格式化字符串而不输出
0%