java 在字符串中找到一个完整的单词java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2765482/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:43:09  来源:igfitidea点击:

Find a complete word in a string java

java

提问by Shekhar

I am writing a piece of code in which i have to find only complete words for example if i have

我正在写一段代码,我必须在其中找到完整的单词,例如,如果我有

String str = "today is tuesday";

and I'm searching for "t" then I should not find any word.

我正在搜索“t”,那么我应该找不到任何词。

Can anybody tell how can I write such a program in java?

谁能告诉我如何用java编写这样的程序?

回答by bl4ckb0l7

I use a regexps for such tasks. In your case it should look something like this:

我将正则表达式用于此类任务。在你的情况下,它应该是这样的:

String str = "today is tuesday";
return str.matches(".*?\bt\b.*?"); // returns "false"

String str = "today is t uesday";
return str.matches(".*?\bt\b.*?"); // returns "true"

A short explanation:

一个简短的解释:

. matches any character, *? is for zero or more times, \b is a word boundary.

. 匹配任何字符,*? 是零次或多次,\b 是单词边界

More information on regexps can be found hereor specifically for java here

对正则表达式的更多信息,可以发现这里还是专门为Java这里

回答by polygenelubricants

    String sentence = "Today is Tuesday";
    Set<String> words = new HashSet<String>(
        Arrays.asList(sentence.split(" "))
    );
    System.out.println(words.contains("Tue")); // prints "false"
    System.out.println(words.contains("Tuesday")); // prints "true"

Each contains(word)query is O(1), so short of implementing your own sophisticated dictionary data structure, this is the fastest most practical solution if you have many words to look for in a text.

每个contains(word)查询都O(1)没有实现您自己复杂的字典数据结构,如果您要在文本中查找很多单词,这是最快最实用的解决方案。

This uses String.splitto separate out the words from the sentence on the " "delimiter. Other possible variations, depending on how the problem is defined, is to use \b, the word boundary anchor. The problem is considerably more difficult if you must take every grammatical features of natural languages into consideration (e.g. "can't"is split by \binto "can"and "t").

这用于String.split" "分隔符上的句子中分离出单词。根据问题的定义方式,其他可能的变化是使用\b,词边界锚。这个问题是相当多的困难,如果你必须把自然语言的每个语法特点考虑在内(例如,"can't"由分裂\b"can""t")。

Case insensitivity can be easily introduced by using the traditional case normalization trick: split and hash sentence.toLowerCase()instead, and see if it contains(word.toLowerCase()).

通过使用传统的大小写规范化技巧:拆分和散列sentence.toLowerCase(),可以很容易地引入不区分大小写的问题,看看它是否contains(word.toLowerCase())

See also

也可以看看

回答by ryanprayogo

String[] tokens = str.split(" ");

for(String s: tokens) {
    if ("t".equals(s)) {
        // t exists
        break;
    }
}

回答by Bozho

String[] words = str.split(" ");
Arrays.sort(words);
Arrays.binarySearch(words, searchedFor);

回答by thelost

String str = "today is tuesday";

StringTokenizer stringTokenizer = new StringTokenizer(str);

bool exists = false;

while (stringTokenizer.hasMoreTokens()) {
    if (stringTokenizer.nextToken().equals("t")) {
        exists = true;
        break;
    }
}

回答by james

use a regex like "\bt\b".

使用像“\bt\b”这样的正则表达式。

回答by Ajay Narang

I would suggest using this regex pattern1 = ".\bt\b." instead of pattern2 = ".?\bt\b.?" . Pattern1 will help you to match the complete String if 't' occurs in that string rather than the pattern2 which just reaches the string "t" you are searching for and ignores rest of the string. There is not much difference in two approaches and for your particular use case of returning true/false will run fine both the ways. The one I suggested will help you to improvise the regex in case you make further changes in your use case

我建议使用这个正则表达式 pattern1 = ". \bt\b." 而不是 pattern2 = ". ?\bt\b.?" . 如果 't' 出现在该字符串中,而不是仅到达您正在搜索的字符串“t”并忽略字符串其余部分的模式 2,则模式 1 将帮助您匹配完整的字符串。两种方法没有太大区别,对于您返回真/假的特定用例,两种方法都可以正常运行。我建议的一个将帮助您即兴编写正则表达式,以防您对用例进行进一步更改

回答by GuruKulki

you can do that by putting a regex which should end with a space.

你可以通过放置一个应该以空格结尾的正则表达式来做到这一点。

回答by private_meta

I would recommend you use the "split"functionality for String with spaces as separators, then go through these elements one by one and make a direct comparison.

我建议您对以空格为分隔符的字符串使用“拆分”功能,然后逐一浏览这些元素并进行直接比较。