java 字符串匹配_查找匹配字符串(Java方法总结)

总结三种方法,之后想把各种算法也总结一下,毕竟笔试中总会遇到。。。。。。

一:IndexOf

用法:

int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。

int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。

int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。

int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

思想:通过返回索引值的个数(非-1)判断有多少个匹配的子串,每次从匹配到的位置再次进行查找

e64c90400af4

通过IndexOf

二:正则表达

用法:

这里用到的是Pattern 和 Matcher ,pattern是一个编译好的正则表达式,而Mather是一个正则表达式适配器,Mather的功能很强大,所以我们一般用pattern 来获取一个Matcher对象,然后用Matcher来操作正则表达式。

思想:编译子串,创建 Matcher 对象,依照正则表达式,该对象可以与任意字符序列匹配

e64c90400af4

通过正则表达式

三:Split

用法:

split() 方法根据匹配给定的正则表达式来拆分字符串。

思想:将分离的字符串放到一个数组中,数组的长度-1为子串在父串中的匹配个数。

e64c90400af4

通过split

整体代码:

package StringMatch;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

/*

* Find the child's count from parent

* @author Amma

*/

public class Main {

//IndexOf

public void ThroughIndexOf(String parent,String child){

int count=0;

int StartIndex=0;

while(parent.indexOf(child,StartIndex)!=-1){

StartIndex = parent.indexOf(child,StartIndex);

StartIndex+=child.length();

count++;

}

System.out.print("The number of matches is:"+count+"\n");

}

//Match

public void ThroughMatch(String parent,String child){

int count=0;

//Compile takes substrings as parameters

Pattern p=Pattern.compile(child);

//Matcher receives the parent string as a parameter

Matcher m=p.matcher(parent);

while(m.find()){

count++;

}

System.out.print("The number of matches is:"+count+"\n");

}

//Split

public void ThroughSplit(String parent,String child){

int count=0;

String[] array=parent.split(child);

count=array.length-1;

System.out.print("The number of matches is:"+count);

}

public static void main(String[] args) {

String P="Amma is my name,I love my family,I love my country!";

String C="my";

Main main=new Main();

System.out.print("****** The result of IndexOf ******"+"\n");

main.ThroughIndexOf(P,C);

System.out.print("****** The result of Match ******"+"\n");

main.ThroughMatch(P,C);

System.out.print("****** The result of Split ******"+"\n");

main.ThroughSplit(P,C);

}

}

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值