它的工作方式是,用户将文本粘贴到cmd中,然后他可以选择其中一个程序选项。其中之一是在文本中查找特定的单词/短语。这是我在本节中的代码:
public void searching() {
System.out.println("Enter the word you wish to find");
Pattern pattern = Pattern.compile(scan.next());
Matcher matcher = pattern.matcher(text);
boolean found = false;
while (matcher.find()) {
System.out.println("I found the text "+pattern+" starting at index "+
matcher.start()+" and ending at index "+matcher.end());
found = true;
}
if(!found){
System.out.println("No match found.");
}
}
我的问题是,如果用户的文本是例如"lorem ipsum dolor sit amet",并且他们想找到单词"dolor"的位置,则输出为"找不到匹配项"。只有当用户要求时,程序才会找到单词lorem。
另一个问题是:有没有办法使输出不是找到的单词的索引,而是整个文本和找到的大写单词?
你正在做。粘贴的代码工作正常。自包含测试用例:
Pattern pattern = Pattern.compile("dolor");
Matcher matcher = pattern.matcher("lorem ipsum dolor sit amet");
boolean found = false;
while (matcher.find()) {
System.out.println("I found the text "+pattern+" starting at index "+
matcher.start()+" and ending at index "+matcher.end());
found = true;
}
if(!found) {
System.out.println("No match found.");
}
它打印:
I found the text dolor starting at index 12 and ending at index 17
然后可以使用索引编写一些代码并操作字符串。您正在寻找:
substring
- 将字符串切成薄片。"hello".substring(1, 4)
变成"ell"。toUpperCase()
- 大写文本。"hello".toUpperCase()
变成"你好">- 连接字符串。只是+就可以了。
"he" + "ll" + "o"
变成"你好">
这些操作就是您所需要的。
首先制作 3 个子字符串:在 'matcher.start()' 之前,在开始和结束之间,在结束之后。然后大写中间的。然后将它们全部连接起来。如果要将所有匹配项大写,请使用类似的技术。也许你想参与StringBuilder
,让你一点一点地建立字符串:
StringBuilder x = new StringBuilder();
x.append("he");
x.append("ll");
x.append("o");
String y = x.toString();
System.out.println(y); // prints "hello"