總結(jié)三種方法,之后想把各種算法也總結(jié)一下茅姜,畢竟筆試中總會遇到闪朱。。钻洒。奋姿。。素标。
一:IndexOf
用法:
int indexOf(String str) :返回第一次出現(xiàn)的指定子字符串在此字符串中的索引称诗。?
int indexOf(String str, int startIndex):從指定的索引處開始,返回第一次出現(xiàn)的指定子字符串在此字符串中的索引头遭。?
int lastIndexOf(String str) :返回在此字符串中最右邊出現(xiàn)的指定子字符串的索引寓免。?
int lastIndexOf(String str, int startIndex) :從指定的索引處開始向后搜索癣诱,返回在此字符串中最后一次出現(xiàn)的指定子字符串的索引。
思想:通過返回索引值的個數(shù)(非-1)判斷有多少個匹配的子串袜香,每次從匹配到的位置再次進行查找
二:正則表達
用法:
? ? ? ? 這里用到的是Pattern 和 Matcher 撕予,pattern是一個編譯好的正則表達式,而Mather是一個正則表達式適配器蜈首,Mather的功能很強大实抡,所以我們一般用pattern 來獲取一個Matcher對象,然后用Matcher來操作正則表達式欢策。
思想:編譯子串,創(chuàng)建 Matcher 對象吆寨,依照正則表達式,該對象可以與任意字符序列匹配
三:Split
用法:
split() 方法根據(jù)匹配給定的正則表達式來拆分字符串踩寇。
思想:將分離的字符串放到一個數(shù)組中啄清,數(shù)組的長度-1為子串在父串中的匹配個數(shù)。
整體代碼:
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);
}
}