创建一个stringFinding方法,该方法期望一个字符串'x'和另一个字符串'find'作为参数并返回布尔值。如果“搜索”的所有字符以相同的顺序出现,但在“ x”中可能以不同的字母出现,则返回值应为真。
我已经尝试过这段代码,除了一个条件外,所有条件都可以正常工作。
import random, time, os
what = ("Your answer is mine!", "I don't quite know..", "Who knows...")
should = ("Yes, yes you should..", "Don't, please don't", "Okay...")
isvar = ("I believe so.", "No, not at all.....")
amvar = ("Yes, definetly", "No, not at all.....")
whyvar = ("Your answer is mine...", "I dont quite know..")
can = ("Yes, indeed", "No.... Idiot!", "Im not sure..")
question = input("The answer resides within your question, which is..?\n:")
first, *middle, last = question.split()
rwhat = random.choice(what)
rshoud = random.choice(should)
ris = random.choice(isvar)
ram = random.choice(amvar)
rwhy = random.choice(whyvar)
rcan = random.choice(can)
first = str(first)
if (first) == "what" or "What":
print (rwhat)
time.sleep(1)
os.system('pause')
elif (first) == "should" or "Should":
print (rshoud)
time.sleep(1)
os.system('pause')
elif (first) == "is" or "Is":
print (ris)
time.sleep(1)
os.system('pause')
elif (first) == "am" or "Am":
print (ram)
time.sleep(1)
os.system('pause')
elif (first) == "why" or "Why":
print (rwhy)
time.sleep(1)
os.system('pause')
elif (first) == "can" or "Can":
print (rcan)
time.sleep(1)
os.system('pause')
这里是条件
public boolean stringFinden(String x, String suchen){
String a = "";
a = x.replaceAll("\\s", "");
if (a.indexOf(suchen) >= 0 ) {
return true;
}
else {
return false;
}
}
输出应为true(接收为true)
System.out.println (stringFinden ("ab c", "abc"));
输出应为假(接收到假)
System.out.println (stringFinden ("ac b", "abc"));
输出应为true(接收为true)
System.out.println (stringFinden ("xxx", ""));
输出应为假(接收到假)
System.out.println (stringFinden ("1234567", "7521"));
但是在这种情况下,我变得虚假了(输出应该为真)
答案 0 :(得分:0)
您需要按顺序检查每个字符,例如:
public static boolean stringFinden(String x, String suchen){
int lastCharIndex = -1;
for (char c : suchen.toCharArray()) {
int currentCharIndex = x.indexOf(c);
if (currentCharIndex > lastCharIndex) {
lastCharIndex = currentCharIndex;
} else {
return false;
}
}
return true;
}