字符串在现实中几乎无所不在,所有文本都可以看做是字符串,因为实用,所以“挺好玩!”。
当然,编程的目的肯定不止为了好玩。
代码如下:
import java.util.Scanner;
/**Java how to program, 10th edition
14.4 (Comparing Portions of Strings) Write an application that uses String
method region-Matches to compare two strings input by the user. The application
should input the number of characters to be compared and the starting index
of the comparison. The application should state whether the strings are equal.
Ignore the case of the characters when performing the comparison.
* @author pandenghuang@163.com*/
public class Test
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("请输入字符串1:");
String s1=input.nextLine();
System.out.print("请输入字符串2:");
String s2=input.nextLine();
System.out.print("请输入起始比较位置:");
int offset=input.nextInt()-1;
System.out.print("请输入要比较的字符数:");
int len=input.nextInt();
boolean result=s1.regionMatches(0, s2, offset, len);
if (result==true)
System.out.printf("字符串1“%s”和字符串2“%s”比较结果:从位置%d开始的%d个字符匹配",s1,s2,offset+1,len);
else
System.out.printf("字符串1“%s”和字符串2“%s”比较结果:从位置%d开始的%d个字符不匹配",s1,s2,offset+1,len);
}
}
运行结果:
Round1:
请输入字符串1:黄双双
请输入字符串2:黄斌斌
请输入起始比较位置:1
请输入要比较的字符数:1
字符串1“黄双宁”和字符串2“黄斌斌”比较结果:从位置1开始的1个字符匹配
Round2:
请输入字符串1:黄双双
请输入字符串2:黄海斌
请输入起始比较位置:1
请输入要比较的字符数:2
字符串1“黄双双”和字符串2“黄海斌”比较结果:从位置1开始的2个字符不匹配