如何使用 Java 匹配字串中的區域



問題描述

如何匹配字串中的區域?

解決方案

以下示例透過使用 regionMatches() 方法,確定兩個字串中的區域匹配。

public class StringRegionMatch {
   public static void main(String[] args) {
      String first_str = "Welcome to Microsoft";
      String second_str = "I work with Microsoft";
      boolean match = first_str.regionMatches(11, second_str, 12, 9);
      System.out.println("first_str[11 -19] == " + "second_str[12 - 21]:-"+ match);
   }
}
  • 11 是比較從其開始的源字串中的索引編號

  • Second_str 是目標字串

  • 12 是比較應從目標字串中開始的索引編號

  • 9 是要比較的字元數

結果

上述程式碼示例將產生以下結果。

first_str[11 -19] == second_str[12 - 21]:-true 
java_strings.htm
廣告
© . All rights reserved.