这是程序,我有一个字符串 strLineText
,我需要从中提取包含 target
的单词。
例如。在字符串“带有 IWANTTHISABC-123 及更多内容的随机字符串”
中,我需要提取 IWANTTHISABC-123
。同样,如果字符串是“带有 IWANTTHISBBC-001 的随机字符串”,我需要提取“IWANTTHISBBC-001”。前缀是固定的
我已尝试使用 substring()
(Method1) 但该逻辑不适用于以此目标单词结尾的字符串即没有输出任何内容
我尝试了 split()
(Method2),它适用于所有四种组合。
你能帮我实现对所有四种组合使用 substring()
(Method1)
public static void main(String[] args) throws IOException {
String target = "IWANTTHIS";
//Four possible inputs
String strLineText = "random string with IWANTTHISABC-123 and more"; //works
String strLineText = "IWANTTHISCBC-45601 and more"; //works
String strLineText = "IWANTTHISEBC-1"; //doesn't work
String strLineText = "random string with IWANTTHISKBC-55545"; //doesn't work
//Method1
System.out.println("O/P 1:" + strLineText.substring(strLineText.indexOf(target),
strLineText.indexOf(target) + strLineText.substring(strLineText.indexOf(target)).indexOf(" ") + 1).trim());
//Method2
for (String s : strLineText.split(" "))
if (s.contains(target))
System.out.println("O/P 2:" + s.trim());
}
最佳答案
我认为这非常简单,您只需要从开始索引开始计算结束索引即可。这是适用于所有情况的代码片段。
int begin = strLineText.indexOf(target);
int end = strLineText.indexOf(" ", begin);
if(end == -1) end = strLineText.length();
System.out.println(strLineText.substring(begin, end));
关于java:检索以特定字符串开头和结尾的字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59340309/