我是全新的,完全迷失了。我正在寻找可以向我解释如何执行此操作的教程或资源:
为每个展开的缩写输出一条消息,然后输出展开的行。
e.g。
Enter text: IDK how that happened. TTYL.
You entered: IDK how that happened. TTYL.
Replaced "IDK" with "I don't know".
Replaced "TTYL" with "talk to you later".
Expanded: I don't know how that happened. talk to you later.
我知道如何执行userText.replace
部分将IDK
更改为I don't know
,但我不知道如何将其设置为搜索{{1}的字符串}
答案 0 :(得分:0)
您可以使用String.indexOf()
查找给定字符串的第一个实例:
String enteredText = "IDK how that happened. TTYL.";
int pos = enteredText.indexOf("IDK"); // pos now contains 0
pos = enteredText.indexOf("TTYL"); // pos now contains 23
如果indexOf()
找不到字符串,则返回-1。
一旦您知道找到了某个值(通过测试pos != -1)
,请执行替换并输出您的信息。
答案 1 :(得分:0)
使用String.indexOf()
检查输入字符串中是否存在每个缩写,replaceAll()
是否修改字符串:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String text = scanner.nextLine();
System.out.println("You entered: " + text);
if(text.indexOf("IDK") != -1) {
System.out.println("Replaced \"IDK\" with \"I don't know\"");
text = text.replaceAll("IDK", "I don't know");
}
if(text.indexOf("TTYL") != -1) {
System.out.println("Replaced \"TTYL\" with \"talk to you later\"");
text = text.replaceAll("TTYL", "talk to you later");
}
System.out.println("Expanded: " + text);
}
}
<强>输出:强>
Enter text: IDK how that happened. TTYL.
You entered: IDK how that happened. TTYL.
Replaced "IDK" with "I don't know"
Replaced "TTYL" with "talk to you later"
Expanded: I don't know how that happened. talk to you later.
试试here!
注意:上述实施不会处理针对该问题的输入的任何不规则大写,我建议您查看toLowerCase()
或toUppperCase()
。