Calculation of Public strings -- String. regionMatches Method & Java tag, stringmatches
Question: enter two strings, calculate the maximum length of the two strings, and output them. The characters are case insensitive.
For example, input abcde xxxBcyyy and Output 2.
Complete Java code:
import java.util.*;public class Main { public static void main(String arg[]){ Scanner s=new Scanner(System.in); String str1=s.next(); String str2=s.next(); s.close(); String maxStr,minStr; if(str1.length()>str2.length()){ maxStr=str1; minStr=str2; } else{ maxStr=str2; minStr=str1; } int max=maxStr.length(); int min=minStr.length();//System.out.println(maxStr+" "+minStr+" "+max+" "+min); int result=0; OK: for(int l=min;l>0;l--){ for(int i=0;i<=max-l;i++){ for(int j=0;j<=min-l;j++){ if(maxStr.regionMatches(true, i, minStr, j, l)){ result=l;//System.out.println(l+" "+i+" "+j); break OK; } } } } System.out.println(result); } }
Learning Point 1: Jump out of multiple loops using Java labels;
Learning Point 2: Use the String. regionMatches method flexibly to determine whether the Sub-String regions of the two strings are equal. For details, refer to the Java API documentation.
RegionMatches
public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
-
Test whether the two string regions are equal.
Set thisStringObject substrings and ParametersOther. If the two substrings represent the same character sequence, the result isTrue, When and only whenIgnoreCaseIf it is true, Case sensitivity is ignored. To compare thisStringSub-string of the object from the indexToffsetAnd the length isLen. To be comparedOtherSub-string from the indexOoffsetAnd the length isLen. The result is true only when at least one of the following is true.False:
- ToffsetIs negative.
- OoffsetIs negative.
- Toffset + lenGreaterStringObject length.
- Ooffset + lenLength greater than the length of another parameter.
- IgnoreCaseIsFalseAnd there isLenNon-negative integerK, That is:
this.charAt(toffset+k) != other.charAt(ooffset+k)
- IgnoreCaseIsTrueAnd there isLenNon-negative integerK, That is:
Character.toLowerCase(this.charAt(toffset+k)) != Character.toLowerCase(other.charAt(ooffset+k))
And: Character.toUpperCase(this.charAt(toffset+k)) != Character.toUpperCase(other.charAt(ooffset+k))
-
-
-
Parameters:
-
ignoreCase-If
trueIs case-insensitive when comparing characters.
-
toffset-The starting offset of the neutron zone of this string.
-
other-String parameter.
-
toffset-The starting offset of the neutron zone of the string parameter.
-
len-The number of characters to be compared.
-
Return Value:
-
If the specified sub-region of the string matches the specified sub-region of the string parameter
trueOtherwise
false. Whether the matching is complete or case sensitive depends on
ignoreCaseParameters.