[英]To check if string contains particular word
So how do you check if a string has a particular word in it?那么如何检查字符串中是否包含特定单词呢?
So this is my code:所以这是我的代码:
a.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(d.contains("Hey")){
c.setText("OUTPUT: SUCCESS!");
}else{
c.setText("OUTPUT: FAIL!");
}
}
});
I'm getting an error.我收到一个错误。
Not as complicated as they say, check this you will not regret.没有他们说的那么复杂,检查这个你不会后悔的。
String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";
if ( sentence.toLowerCase().indexOf(search.toLowerCase()) != -1 ) {
System.out.println("I found the keyword");
} else {
System.out.println("not found");
}
You can change the toLowerCase()
if you want.如果需要,您可以更改
toLowerCase()
。
.contains()
is perfectly valid and a good way to check. .contains()
是完全有效的,是一种很好的检查方法。
( http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence) ) ( http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence) )
Since you didn't post the error, I guess d
is either null or you are getting the "Cannot refer to a non-final variable inside an inner class defined in a different method" error.由于您没有发布错误,我猜
d
要么为空,要么您收到“无法引用以不同方法定义的内部类中的非最终变量”错误。
To make sure it's not null, first check for null in the if statement.为了确保它不为空,首先检查 if 语句中的空值。 If it's the other error, make sure
d
is declared as final
or is a member variable of your class.如果是另一个错误,请确保
d
被声明为final
或者是您的类的成员变量。 Ditto for c
.同上
c
。
You can use regular expressions:您可以使用正则表达式:
if (d.matches(".*Hey.*")) {
c.setText("OUTPUT: SUCCESS!");
} else {
c.setText("OUTPUT: FAIL!");
}
.*
-> 0 or more of any characters .*
-> 0 个或多个任意字符
Hey
-> The string you want Hey
-> 你想要的字符串
If you will be checking this often, it is better to compile the regular expression in a Pattern
object and reuse the Pattern
instance to do the checking.如果你经常检查这个,最好在
Pattern
对象中编译正则表达式Pattern
用Pattern
实例来进行检查。
private static final Pattern HEYPATTERN = Pattern.compile(".*Hey.*");
[...]
if (HEYPATTERN.matcher(d).matches()) {
c.setText("OUTPUT: SUCCESS!");
} else {
c.setText("OUTPUT: FAIL!");
}
Just note this will also match "Heyburg"
for example since you didn't specify you're searching for "Hey"
as an independent word.请注意,这也将匹配
"Heyburg"
,例如,因为您没有指定您正在搜索"Hey"
作为一个独立的词。 If you only want to match Hey
as a word, you need to change the regex to .*\\\\bHey\\\\b.*
如果只想匹配
Hey
作为单词,则需要将正则表达式更改为.*\\\\bHey\\\\b.*
Using contains使用包含
String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";
if (sentence.toLowerCase().contains(search.toLowerCase())) {
System.out.println("I found the keyword..!");
} else {
System.out.println("not found..!");
}
The other answer (to date) appear to check for substrings rather than words.另一个答案(迄今为止)似乎检查子字符串而不是单词。 Major difference.
主要区别。
With the help of this article , I have created this simple method:在本文的帮助下,我创建了这个简单的方法:
static boolean containsWord(String mainString, String word) {
Pattern pattern = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE); // "\\b" represents any word boundary.
Matcher matcher = pattern.matcher(mainString);
return matcher.find();
}
String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";
Compare the line of string in given string比较给定字符串中的字符串行
if ((sentence.toLowerCase().trim()).equals(search.toLowerCase().trim())) {
System.out.println("not found");
}
else {
System.out.println("I found the keyword");
}
It's been correctly pointed out above that finding a given word in a sentence is not the same as finding the charsequence, and can be done as follows if you don't want to mess around with regular expressions.上面已经正确指出,在句子中查找给定的单词与查找字符序列不同,如果您不想弄乱正则表达式,可以按如下方式完成。
boolean checkWordExistence(String word, String sentence) {
if (sentence.contains(word)) {
int start = sentence.indexOf(word);
int end = start + word.length();
boolean valid_left = ((start == 0) || (sentence.charAt(start - 1) == ' '));
boolean valid_right = ((end == sentence.length()) || (sentence.charAt(end) == ' '));
return valid_left && valid_right;
}
return false;
}
Output :输出:
checkWordExistence("the", "the earth is our planet"); true
checkWordExistence("ear", "the earth is our planet"); false
checkWordExistence("earth", "the earth is our planet"); true
PS Make sure you have filtered out any commas or full stops beforehand. PS确保您事先过滤掉了任何逗号或句号。
Solution-1: - If you want to search for a combination of characters or an independent word from a sentence.解决方案 1: - 如果您想从句子中搜索字符组合或独立单词。
String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".*Beneficent.*")) {return true;}
else{return false;}
Solution-2: - There is another possibility you want to search for an independent word from a sentence then Solution-1 will also return true if you searched a word exists in any other word.解决方案 2: - 还有另一种可能性,您想从句子中搜索一个独立的单词,如果您搜索的某个单词存在于任何其他单词中,则解决方案 1也将返回 true。 For example, If you will search cent from a sentence containing this word ** Beneficent** then Solution-1 will return true.
例如,如果您要从包含这个词 ** Beneficent** 的句子中搜索cent ,那么Solution-1将返回 true。 For this remember to add space in your regular expression.
为此,请记住在正则表达式中添加空格。
String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".* cent .*")) {return true;}
else{return false;}
Now in Solution-2 it wll return false because no independent cent word exist.现在在解决方案 2 中,它将返回false,因为不存在独立的分词。
Additional : You can add or remove space on either side in 2nd solution according to your requirements.附加:您可以根据您的要求在第二个解决方案中添加或删除任一侧的空间。
if (someString.indexOf("Hey")>=0)
doSomething();
Maybe this post is old, but I came across it and used the "wrong" usage.也许这篇文章很旧,但我遇到了它并使用了“错误”的用法。 The best way to find a keyword is using
.contains
, example:查找关键字的最佳方法是使用
.contains
,例如:
if ( d.contains("hello")) {
System.out.println("I found the keyword");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.