[英]Find occurence of substring in string using indexOf and substring in java
[英]java indexOf ignores the first occurence
这是我的代码。 它看起来如此重复。 有没有办法让它看起来更干净? 谢谢。 我的代码应该做这样的事情;
输入文字:IDK if I will go。 这是我BFF的生日。
你输入:IDK if I'll go。 这是我BFF的生日。
BFF:永远最好的朋友
IDK:我不知道
import java.util.Scanner;
public class TextMsgDecoder {
public static void main(String[] args) {
/* Type your code here. */
String a = "BFF";
String b = "IDK";
String c = "JK";
String d = "TMI";
String e = "TTYL";
Scanner scr = new Scanner(System.in);
System.out.println("Enter text:");
String f = scr.nextLine();
System.out.println("You entered: "+ f);
if(f.indexOf(a)>=0)
System.out.println("BFF: best friend forever");
if(f.indexOf(b)>=0)
System.out.println("IDK: I don't know");
if(f.indexOf(c)>=0)
System.out.println("JK: just kidding");
if(f.indexOf(d)>=0)
System.out.println("TMI: too much information");
if(f.indexOf(e)>=0)
System.out.println("TTYL: talk to you later");
return;
}
}
只是重复评论中所说的(因为评论可能会被清理),
if(f.indexOf(e)>0)
实际上应该是
if(f.indexOf(e)>=0)
或者,更好的是,只需使用string.contains
。
第三种选择是创建哈希表。 我不是坐在 IDE 前,而是在手机上写这个,但这是一个粗略的想法(使用更接近 C# 语法而不是“直接”Java):
// A C# Dictionary is a hash table
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("BFF", "Best Friend Forever");
// Add the rest of the abbreviations
// Loop over every key (abbreviation) in the hash table
foreach (string abbreviation in dict.Keys) {
// If the string contains the abbreviation
if (f.contains(abbreviation)) {
Console.WriteLine(abbreviation + ": " + dict[key]);
}
}
如果稍后添加更多缩写,这将更容易阅读/更简洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.