如何在用户输入的字符之间输出单词,例如,输入为4(选项#(、dog *is* sleeping
(短语(、*(字符(输出应为is
。这个任务只能使用子字符串方法来完成,不能使用循环或其他任何方法。
这是我的代码:
else if (option == 4){
String x = keyboard.next();
int counter = 0;
sub = phrase.substring(0, phrase.length());
if (sub == x)
counter++;
else if (counter == 1)
System.out.print(sub);
}
我使用for循环完成了这项任务,但现在我只想使用子字符串方法,我将向你展示使用for循环的代码,这样你就有了更好的想法:
else if (option == 4){
char x = keyboard.next().charAt(0);
int z = 0;
for (int y = 0; y < phrase.length(); y++){
char n = phrase.charAt(y);
if (n == x)
z++;
else if (z == 1)
System.out.print(n);
}
}
有两个版本的子字符串。第一个需要一个索引,第二个需要两个索引。我使用了一个需要两个索引的索引,第一个索引(包含索引(表示开始,第二个索引(排除索引(表示结束。
按如下操作:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter option: ");
int option = Integer.parseInt(keyboard.nextLine());
if (option == 4) {
System.out.print("Enter phrase: ");
String phrase = keyboard.nextLine();
System.out.print("Enter character: ");
String letter = keyboard.nextLine();
int index1 = phrase.indexOf(letter);
int index2 = phrase.indexOf(letter, index1 + 1);
System.out.println("The required word is '" + phrase.substring(index1 + 1, index2) + "'");
}
}
}
样本运行:
Enter option: 4
Enter phrase: dog *is* sleeping
Enter character: *
The required word is 'is'