Java 如何从字符串中查找特定单词
我想检查特定单词是否存在于带有ignore case的字符串中 我的字符串是“你好,世界,Wassup?,早上好” 现在我想检查一下“你好,世界”这个词 因此,我尝试了以下方法:Java 如何从字符串中查找特定单词,java,android,Java,Android,我想检查特定单词是否存在于带有ignore case的字符串中 我的字符串是“你好,世界,Wassup?,早上好” 现在我想检查一下“你好,世界”这个词 因此,我尝试了以下方法: String fullText = "Hello world , Wassup? , good moRNING"; String singleWord = "hello world"; boolean find; if (fullText.matches(singleWord)) { find = Tru
String fullText = "Hello world , Wassup? , good moRNING";
String singleWord = "hello world";
boolean find;
if (fullText.matches(singleWord)) {
find = True;
}
我也尝试过使用contains
,但这不起作用
我怎样才能找到这个词呢?你可以尝试将要搜索的句子和字符串的大小写都改为小写,例如
if (fullText.toLowerCase().matches(singleWord.toLowerCase())) {
find = True;
}
您可以尝试将要搜索的句子和字符串的大小写降低,例如
if (fullText.toLowerCase().matches(singleWord.toLowerCase())) {
find = True;
}
问题在于: Hello-world不包含Hello-world,因为它有大写字母 使用以下命令:
if (fullText.toLowerCase().matches(singleWord.toLowerCase())) {
find = True;
}
问题在于: Hello-world不包含Hello-world,因为它有大写字母 使用以下命令:
if (fullText.toLowerCase().matches(singleWord.toLowerCase())) {
find = True;
}
您可以尝试以下方法:
String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0; // true if contains
// Anywhere in string
b = string.matches("(?i).*i am.*"); // true if contains but ignore case
// Anywhere in string
b = string.contains("AA") ;
您可以尝试以下方法:
String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0; // true if contains
// Anywhere in string
b = string.matches("(?i).*i am.*"); // true if contains but ignore case
// Anywhere in string
b = string.contains("AA") ;
您可以将这两个字符串转换为普通大小写,然后使用
indexOf
或其他匹配的字符串。您需要使用regex。
String fullText = "Hello world , Wassup? , good moRNING";
String singleWord = "hello world";
boolean find;
if (fullText.toLowerCase().indexOf(singleWord.toLowerCase()) > -1) {
find = true;
}
您可以将这两个字符串转换为普通大小写,然后使用
indexOf
或其他匹配的字符串。您需要使用regex。
String fullText = "Hello world , Wassup? , good moRNING";
String singleWord = "hello world";
boolean find;
if (fullText.toLowerCase().indexOf(singleWord.toLowerCase()) > -1) {
find = true;
}
试试谷歌,看看这里:hello和hello不同于小写和大写的区别
h
(正如@AdityaVyas Lakhan指出的),contains()
应该可以工作matches()
不适合,因为它(a)需要正则表达式,并且(b)只有在整个字符串与正则表达式匹配时才返回true,也就是说,前后不包含更多字符。这是一个旁白:true
应该带有一个小的t
(不敢相信有多少答案复制了这个错误).试试谷歌,看看这里:hello和hello与小写和大写的区别不同h
(正如@AdityaVyas Lakhan指出的),contains()
应该可以工作matches()
不适合,因为它(a)需要正则表达式,并且(b)只有在整个字符串与正则表达式匹配时才返回true,也就是说,前后不包含更多字符。这是一个旁白:true
应该带有一个小的t
(不敢相信有多少答案复制了这个错误)。应该可以工作(aprat来自True
中的大写T
)。如果使用Java 5或更高版本,contains()
更简单。@OleV.V.感谢您指出。我编辑了代码。应该有效(aprat来自True
中的大写T
)。如果使用Java 5或更高版本,contains()
更简单。@OleV.V.谢谢你指出这一点。我编辑了代码。对我来说效果很好,谢谢你对我来说很好,谢谢