Java 實例 - 測試兩個字串區域是否相等
以下實例使用了 regionMatches() 方法測試兩個字串區域是否相等:
StringRegionMatch.java 檔
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);
}
}
first_str.regionMatches(11, second_str, 12, 9) 表示將 first_str 字串從第11個字元"M"開始和 second_str 字串的第12個字元"M"開始逐個比較,共比較 9 對字元,由於字串區分大小寫,所以結果為false。
如果設置第一個參數為 true ,則表示忽略大小寫區別,所以返回 true。
以上代碼實例輸出結果為:
區分大小寫返回值:false 不區分大小寫返回值:true