题目
查找子字符串的位置
解答
public class FindStr {
public static void main(String[] args) {
System.out.println(strStr("source", "target"));
}
public static int strStr(String source, String target) {
// write your code here
if (source==null||target==null){
return -1;
}
char[] sources = source.toCharArray();
char[] targets = target.toCharArray();
if ((sources.length==targets.length)&&(sources.length==0)){
return 0;
}
for (int i = 0; i < sources.length; i++) {
boolean isExist = true;
for (int j = 0; j < targets.length; j++) {
if((i+j)>=sources.length){
isExist= false;
break;
}
if (sources[i+j] != targets[j]) {
isExist = false;
break;
}
}
if (isExist){
return i;
}
}
return -1;
}
}
本文介绍了一个简单的Java程序,用于查找一个字符串是否包含另一个字符串,并返回该子字符串在源字符串中的起始位置。如果未找到子字符串,则返回-1。通过双重循环实现了基本的字符串匹配过程。

被折叠的 条评论
为什么被折叠?



