[英]Two string region compare in java
我有兩個字符串(str1,str2),用例是這樣的
1)比較str1中的最后i個字符和str2中的前i個字符
2)比較str1中的前i個字符和str2中的后i個字符
我知道如何在C ++中執行以下操作
int len1 = str1.length();
int len2 = str2.length();
1)
str1.compare(len1-i, i, str2, 0, i)
2)
str1.compare(0, i, str2, len2-i, i)
如何使用regionMatches方法或其他方法在Java中實現相同的功能。 無法弄清楚。
通過簡單地查看API文檔,應該很容易弄清楚。 ;)
https://docs.oracle.com/javase/10/docs/api/index.html?java/lang/String.html
您至少有兩個選擇:
一種)
str1.endsWith(str2.substring(i))
str2.endsWith(str1.substring(i))
B)
假設(因此未驗證)兩個字符串至少包含i個字符:
str1.regionMatches(0, str2, str2.length() - i - 1, i)
str1.regionMatches(str1.lenght() - i - 1, str2, 0, i)
在Java中,您可以通過regionMatches完成它:
String str1 = new String("Hello, How are you");
String str2 = new String("How do you do?");
System.out.print("Result of Test1: " );
System.out.println(str1.regionMatches(7, str2, 0, 3));
結果:
Result of Test1: true
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.