[英]conditional logic and string operations in JAVA
我是全新的,完全迷路了。 我正在寻找可以向我解释如何执行此操作的教程或资源:
为每个展开的缩写输出一条消息,然后输出展开的行。
例如
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
,但我不知道如何设置它以搜索IDK
的字符串
您可以使用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)
,执行替换并输出消息。
使用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.
注意:上面的实现不处理该问题的任何大写输入,我建议您研究toLowerCase()
或toUppperCase()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.