注意:此問題需要提供學校作業。我墮落了,我越來越接近真實的代碼,只剩下幾點要照顧。在不使用lastIndexOf方法的情況下打印字符串中的最後一個索引
我要求寫接收兩個字符串(S1和S2),並檢查 S2是否是在S1中情況下敏感的方法。如果s2在s1中,它返回s2最後一次出現的索引,否則返回-1。
所以,這裏是我的代碼:
import java.util.*;
public class homework4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("\nEnter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.println("Enter firts string: ");
String s1 = input.next();
System.out.println("Enter second string: ");
String s2 = input.next();
System.out.print(contains(s1,s2));
}
else {
//Call other methods...
}
public static int contains (String s1, String s2) {
for(int i = 0; i<s1.length(); i++) {
for(int j = 0; j<s2.length(); j++) {
char ch = s2.charAt(j);
if(s1.charAt(i) == ch) {
return i;
}
}
}
return -1;
}
但是這個方法返回的S2第一個索引,或者它僅僅是一個的IndexOf方法的副本。 s1 = aabbccbbe
和s2 = bb
的輸出是2
。
編輯:@利的代碼
import java.util.*;
public class homework4 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("\nEnter a choice: ");
int choice = input.nextInt();
if(choice == 1) {
System.out.println("Enter firts string: ");
String s1 = input.next();
System.out.println("Enter second string: ");
String s2 = input.next();
System.out.print(contains(s1,s2));
}
else {
//Call other methods...
}
public static int contains(String s1, String s2) {
int i = s2.length()-1, j = s1.length()-1;
if(i > j)
return -1;
for(; i > -1; i--) {
for(; j >= 0; j--) {
if(s1.charAt(j) == s2.charAt(i)) {
if(i == 0)
return j;
if(j != 0)
j--;
break;
} else if(i != s2.length()) {
i = s2.length()-1;
}
}
}
return -1;
}
'包含(「問候」,「錯誤」)'返回'2'我認爲,即使'「問候」'不含'「錯誤」',它應該因此返回'-1'。 – Gendarme
@Gendarme'contains(「Greetings」,「error」)'returned'1'。 – f1r4tc
是的,你說得對。更奇怪。它返回它們都有的第一個字母's1'中的索引,在這種情況下是'r'。 – Gendarme