Java源码-判断两个字符串的子字符串是否匹配(Comparing Portions of Strings)
2016-08-09 00:01
453 查看
字符串在现实中几乎无所不在,所有文本都可以看做是字符串,因为实用,所以“挺好玩!”。
当然,编程的目的肯定不止为了好玩。
代码如下:
运行结果:
Round1:
请输入字符串1:黄双双
请输入字符串2:黄斌斌
请输入起始比较位置:1
请输入要比较的字符数:1
字符串1“黄双宁”和字符串2“黄斌斌”比较结果:从位置1开始的1个字符匹配
Round2:
请输入字符串1:黄双双
请输入字符串2:黄海斌
请输入起始比较位置:1
请输入要比较的字符数:2
字符串1“黄双双”和字符串2“黄海斌”比较结果:从位置1开始的2个字符不匹配
当然,编程的目的肯定不止为了好玩。
代码如下:
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个字符不匹配
相关文章推荐
- LeetCode-Isomorphic Strings:判断两个字符串是否同构(hashtable实现)
- Arrays_Strings 判断两个字符串是否有相同的字符 @CareerCup
- java中需要用equals来判断两个字符串值是否相等
- java中判断两个字符串是否相等的问题
- 205. Isomorphic Strings | 判断两个字符串形式是否相同
- java 判断两个字符串是否由相同的字符组成 排序算法 空间换时间的方法
- java中需要用equals来判断两个字符串值是否相等
- java中判断两个字符串是否相等的问题
- java中判断两个字符串是否相等的问题
- java 程序题 判断两个字符串是否是同构的(isIsomorphic)
- java中需要用equals来判断两个字符串值是否相等
- java中判断两个字符串是否相等的问题
- JAVA如何判断两个字符串是否相等
- java中判断两个字符串是否相等的问题
- [leetcode 318]Maximum Product of Word Lengths--判断两个字符串是否有相同的字符
- Java 判断两个字符串是否由相同的字符组成
- JAVA如何判断两个字符串是否相等
- 判断两个字符串是否相等【JAVA】
- java中判断两个字符串是否相等的问题
- 判断两个字符串是否相等【JAVA】