Home >Java >javaTutorial >Example sharing of how to determine whether a string contains a substring in Java

Example sharing of how to determine whether a string contains a substring in Java

黄舟
黄舟Original
2017-08-20 09:39:462238browse

This article mainly introduces relevant information about Java's method of determining whether a string contains a substring. Here are three methods to help you achieve such a function. Friends in need can refer to it

java Method to determine whether a string contains a substring

Method one:


 String  str1  =  "nihaoksdoksad "; 
 String  str2  =  "ok "; 
 int  total  =  0; 
 for  (String  tmp  =  str1;  tmp  !=  null&&tmp.length()> =str2.length();){ 
  if(tmp.indexOf(str2)  ==  0){ 
    total  ++; 
  } 
  tmp  =  tmp.substring(1); 
} 
System.out.println(str1+ "中含有 "+total+ "个 "+str2);

Method two :


String  str1  =  "nihaokokosdokosad "; 
String  str2  =  "oko "; 
int  total  =  0; 
for  (String  tmp  =  str1;  tmp  !=  null&&tmp.length()> =str2.length();){ 
  if(tmp.indexOf(str2)  ==  0){ 
    total  ++; 
    tmp  =  tmp.substring(str2.length()); 
  }else{ 
    tmp  =  tmp.substring(1); 
  } 
} 
System.out.println(str1+ "中含有 "+total+ "个 "+str2);

Method three:


String  str1  =  "nihaoksdoksad "; 
char  []c=str1.toCharArray(); 
int  total=0; 
for(int  i=0;i <c.length-1;i++) 
if(c[i]== &#39;o &#39;&&c[i+1]== &#39;k &#39;) 
total++; 
System.out.println(str1+ "中含有 "+total+ "个ok ");

The above is the detailed content of Example sharing of how to determine whether a string contains a substring in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn