62,615
社区成员
发帖
与我相关
我的任务
分享
public class Search {
//定义计数器
private int i = 0 ;
private int j = 0 ;
//第一个字母
private boolean first ;
public boolean searchChar(String target,String source){
for(;j<source.length() - target.length() + 1;j++){
if(target.charAt(0) == source.charAt(j) ){
first = true;
break;
}
}
if( first == true ){
if(target.length() == 1){
return true;
}
else{
for(i=1,j++;i<target.length();i++,j++){
if(target.charAt(i) != source.charAt(j)){
return false;
}
}
return true;
}
}
else{
return false;
}
}
}
public class Test {
public static void main(String[] args) {
Search search = new Search();
System.out.println(search.isSubString("The", "The cat in the hat."));
System.out.println(search.isSubString("hat.", "The cat in the hat."));
System.out.println(search.isSubString("cat in th", "The cat in the hat."));
}
}
class Search {
public boolean isSubString(String str, String src) {
int index = 0;
while (index < src.length()) {
int lastIndex = index;
for (int i = 0; i < str.length();++i) {
if (str.charAt(i) != src.charAt(index + i)) {
index += (i + 1);
break;
}
}
if (lastIndex == index) {
return true;
}
}
return false;
}
}
public class Search {
//定义计数器
private int i = 0 ;
private int j = 0 ;
//临时存储
private int a = 0 ;
private int b = 0 ;
//循环计数器
private int count = 0 ;
public boolean searchChar(String target,String source){
for(;j<source.length() - target.length() + 1;j++){
if( target.charAt(0) == source.charAt(j)){
a = i+1;
b = j+1;
while ( a < target.length() && target.charAt(a) == source.charAt(b)){
a++;
b++;
count++;
}
if(count == target.length()-1 ){
return true;
}
else{
continue;
}
}
}
return false;
}
}
public class Test {
public static boolean isSubString(String target,String source){
//每次前进一个字符判断
for(int i=0,j=source.length(),k=target.length();i+k<=j;i++){
//取出一个子串
String current=source.substring(i, i+k);
//如果子串等于target则证明是子字符串
if(current.equals(target)){
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.println(isSubString("The", "The cat in the hat."));
System.out.println(isSubString("hat.", "The cat in the hat."));
}
}
而且String类中本身有子字符串的判断方法,contains()