JAvaプログラミング--A文字列の中でB文字列と同じものを見つけて、B文字列が現れた最初の位置を返します.
1149 ワード
1つ与える haystack文字列とneedle文字列haystack文字列 * needle文字列が表示される最初の場所を見つけます(0から).存在しない場合は、 -1. * needleが空の文字列である場合、0を返します.
package com.henu;
/**
* @author limengdong
* @description: haystack needle , haystack
* needle ( 0 )。 , -1。
* needle 0 。
*/
public class Demo07 {
public static void main(String[] args) {
String hayStack = "helohello";
String needle = "ello";
// pl, flag
int pl = 0;
// index,
int index = 0;
for (int i = 0; i < hayStack.length(); i++) {
index = i;// i needle hayStack
String str = "";
for (int j = i; str.length() < needle.length(); j--) {
if (j >= 0) {
str = hayStack.charAt(j) + str;
}else {
break;
}
}
if (needle.equals(str)) {
pl = 1;
break;
}else {
pl = 0;
}
}
if (needle == "") {
System.out.println("0");
}else if (pl == 1) {
System.out.println(index+1-needle.length());
}else {
System.out.println(-1);
}
}
}