从.Contains()语句仅获取整个单词 [英] Get only Whole Words from a .Contains() statement

查看:120
本文介绍了从.Contains()语句仅获取整个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用.Contains()来查找句子中是否包含特定单词,但是我发现了一些奇怪的东西:

I've used .Contains() to find if a sentence contains a specific word however I found something weird:

我想查找单词 hi 出现在如下句子中:

I wanted to find if the word "hi" was present in a sentence which are as follows:


孩子想在泥里玩耍

The child wanted to play in the mud

你好

赫克托特有髋关节问题



if(sentence.contains("hi"))
{
   //
}

我只希望过滤第二个句子,但是由于CHILD中有一个 hi,而臀部中有一个 hi,所以所有3个都被过滤了。我该如何使用.Contains()以便只挑选整个单词?

I only want the SECOND sentence to be filtered however all 3 gets filtered since CHILD has a 'hi' in it and hip has a 'hi' in it. How do I use the .Contains() such that only whole words get picked out?

推荐答案

您可以将句子拆分成单词-您可以在每个空格处拆分,然后修剪所有标点符号。然后检查以下任何单词是否为 hi:

You could split your sentence into words - you could split at each space and then trim any punctuation. Then check if any of these words are 'hi':

var punctuation = source.Where(Char.IsPunctuation).Distinct().ToArray();
var words = sentence.Split().Select(x => x.Trim(punctuation));
var containsHi = words.Contains("hi", StringComparer.OrdinalIgnoreCase);

在此处查看有效的演示: https://dotnetfiddle.net/AomXWx

See a working demo here: https://dotnetfiddle.net/AomXWx

这篇关于从.Contains()语句仅获取整个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆