如何使用Java检查句子中是否存在单词?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23379518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a word is present in a sentence using Java?
提问by user2966197
I am new to programming and working on a function to return true if a word is present in a sentence. I tried the indexOf()
method, but then I also came across a certain issue with this approach:
我是编程新手,正在研究一个函数,如果一个词出现在句子中,则返回 true。我尝试了该indexOf()
方法,但后来我也遇到了这种方法的某个问题:
Suppose my sentence is I am a, Java Programmer.
假设我的句子是 I am a, Java Programmer.
If we look for the word ram
with the indexOf()
method then it will return true
because ram
is present in Programmer
while the correct output should be false
as ram
is not present as a word but as a pattern.
如果我们看一下这个词ram
用的indexOf()
方法,那么它将返回true
因为ram
存在Programmer
而应该是正确的输出false
为ram
不存在的词,但作为一种模式。
How can I work around this problem? The code that I am using as of now is:
我该如何解决这个问题?我现在使用的代码是:
boolean isPresent(String word, String sentence)
{
if(sentence.indexOf(word) >= 0)
return true;
else
return false;
}
NOTE:The word ram
is just an example to show one of the issue with my current approach.It's not that I have to work with ram
only all the time.The word can be any like say a
which is followed by a comma in above sentence.
注意:这个词ram
只是一个例子来说明我当前方法的一个问题。这不是我必须一直使用ram
。这个词可以是任何像 saya
在上面的句子中后面跟一个逗号的词。
UPDATE:Thanks everyone for providing their comments and solutions. I have selected one as an accepted answer(would have selected more if permitted :-)), but a lot were helpful.
更新:感谢大家提供他们的意见和解决方案。我选择了一个作为可接受的答案(如果允许的话,我会选择更多:-)),但很多都是有帮助的。
采纳答案by Evgeniy Dorofeev
try regex
尝试正则表达式
boolean contains = s.matches(".*\bram\b.*");
\b means word boundary
\b 表示单词边界
回答by awksp
Take a look at the String.matches()
method. If you construct the regular expression properly it should be able to do what you want it to. A good place to start for regular expressions would be the Java tutorials: http://docs.oracle.com/javase/tutorial/essential/regex/
看一下String.matches()
方法。如果您正确构造正则表达式,它应该能够做您想做的事情。开始学习正则表达式的好地方是 Java 教程:http: //docs.oracle.com/javase/tutorial/essential/regex/
回答by ashishmaurya
use contains method
使用contains 方法
boolean isPresent(String word, String sentence)
{
return sentence.contains(word);
}
EDIT:
if you want to search for a pariticular word then you can add space befaore and after the word string
word = " " + word + " ";
编辑:如果你想搜索一个特定的单词,那么你可以在单词字符串
word = " " + word + " "之前和之后添加空格;
回答by Scary Wombat
Try this solution
试试这个解决方案
int index = sent.indexOf(find);
if (index != -1) {
if (index == 0) {
System.out.println("true");
}
else if (index + find.length() == sent.length())
{
System.out.println("true");
}
else if (sent.charAt(index - 1) == ' ' && sent.charAt(find.length() + index) == ' ') {
System.out.println("true");
} else {
System.out.println("false");
}
} else {
System.out.println("false");
}
If you want something more than you original question then instead for checking for spaces you should check that they are not between 0-9 and a-Z, this should cover any characters such as comma period etc.
如果您想要的不仅仅是原始问题,那么为了检查空格,您应该检查它们是否不在 0-9 和 aZ 之间,这应该涵盖任何字符,例如逗号句点等。
回答by learner
String s="I am a JAVA programmer";
String s1="JAVA";
String []p=s.split("\s*(=>|,|\s)\s*");
for(int i=0;i<p.length;i++)
{
if(s1.equals(p[i]))
{
System.out.println(p[i]);
}
}
回答by jhonis.souza
A more simpler approach is: if you consider that a word is something like
更简单的方法是:如果您认为一个词类似于
"My pc there is rammemory" (between spaces)
“我的电脑有RAM内存”(空格之间)
you could concat into your indexOf function spaces before and after the word that you are searching, like this
您可以在要搜索的单词前后连接到 indexOf 函数空间,如下所示
if (sentence.indexOf(" "+ word +" ") >= 0) {
if (sentence.indexOf(" "+ word +" ") >= 0) {
回答by joepeacock001
This is a rather clumsy workaround, but should achieve the right results. Find the substring you are looking for within the string, and find the charachters before and after your substring. Check these using their ascii values (int)substring.charAt(x);
to see if they are letters or not. If they are both eithr not letters, or fall outside the bounds of the string, you know you have found a word. Otherwise, you know that it is simply part of a word.
这是一个相当笨拙的解决方法,但应该能达到正确的结果。在字符串中找到您要查找的子字符串,并找到子字符串前后的字符。使用它们的 ascii 值检查它们(int)substring.charAt(x);
是否是字母。如果它们都不是字母,或者不在字符串的范围内,那么您就知道找到了一个单词。否则,您知道它只是单词的一部分。
The logic will be very long- which is why I am not coding it for you, but give this a shot and let me know if you need clarification.
逻辑会很长——这就是为什么我不为你编码,但请试一试,如果你需要澄清,请告诉我。
回答by broomweed
If you want to match a word in a sentence even with punctuation, you'll need a regex like this:
如果你想在句子中匹配一个带有标点符号的单词,你需要一个像这样的正则表达式:
static boolean matchesWord(String toMatch, String matchIn) {
return Pattern.matches(".*([^A-Za-z]|^)"+toMatch+"([^A-Za-z]|$).*", matchIn);
}
(You could use \W, but that doesn't count underscores as punctuation.)
(您可以使用 \W,但这不会将下划线视为标点符号。)
Just concatenating spaces onto the beginning and the end won't match, for example, the word "programmer" in the string "I am a Java programmer" because there's no space at the end. It also won't match words directly before or after punctuation.
仅将空格连接到开头和结尾是不匹配的,例如,字符串“我是 Java 程序员”中的“程序员”一词,因为末尾没有空格。它也不会直接匹配标点符号之前或之后的单词。
回答by Zaheer Ahmed
Since you want to search a word there are three cases:
由于您要搜索一个单词,因此有以下三种情况:
- word at start of sentence means no space at start but space at end.
- word between the sentence space at both ends.
- word at end only space at end.
- 句子开头的单词意味着开头没有空格而结尾有空格。
- word两端的句子空间之间。
- 词尾只有空格。
To cover all the three cases, one possible solution is:
为了涵盖所有三种情况,一种可能的解决方案是:
String str = "I am a JAVA programmer";
String[] splited = str.split("\b+"); //split on word boundries
Arrays.asList(splited).contains("ram"); //search array for word
回答by Tina Maria
This will work, assuming that each word is separated by a space. I've added the main function for clarity. The find_str returns -1 if the word doesn't exist. otherwise, it returns the position of the word with respect to other words. Here, 2 will be returned, meaning that the second word is 'am'.
这将起作用,假设每个单词都用空格分隔。为了清楚起见,我添加了主要功能。如果单词不存在,则 find_str 返回 -1。否则,它返回单词相对于其他单词的位置。在这里,将返回 2,这意味着第二个单词是“am”。
import java.util.*;
public class HelloWorld{
public static void main(String []args){
String str="I am a Java Programmer";
String str1="am";
int x=find_str(str,str1);
System.out.println(x);
}
public static int find_str(String main,String search) {
int i;
int found=-1;
String[] s=main.split(" ");
for(i=0;i<s.length;i++)
{
if(search.equals(s[i]))
found=i+1;
}
return found;
}
}
回答by Karthikeyan Sukkoor
Hlo. You can split the sentence as array and then you put into List. after that you can use contains method to check you word is present or not. Kindly try this code..
喂。您可以将句子拆分为数组,然后放入列表。之后,您可以使用 contains 方法来检查您的单词是否存在。请试试这个代码..
import java.util.ArrayList;
import java.util.Arrays;
public class karthitest {
public static void main(String[] args) {
String sentence = "I am Karthick";
String word = "I";
if(isWordExist(sentence, word)){
System.out.println("Word is exist");
}
}
public static boolean isWordExist(String sentence, String word){
boolean ans = Boolean.FALSE;
ArrayList<String> wordList = null;
try {
if(sentence != null && word != null){
wordList = new ArrayList<String>(Arrays.asList(sentence.split("[^a-zA-z]+")));
if(wordList.contains(word)){
ans = Boolean.TRUE;
}
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
return ans;
}
}