Java源码-判断两个字符串的子字符串是否匹配(Comparing Portions of Strings)

字符串在现实中几乎无所不在,所有文本都可以看做是字符串,因为实用,所以“挺好玩!”。

当然,编程的目的肯定不止为了好玩。


代码如下:

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个字符不匹配



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值