繁体   English   中英

如何检查字符串是否包含C#Winforms中的文本

[英]How to check if string contains the text in C# Winforms

谁能帮我用C#Winforms编写一段代码,该代码可以给我一个布尔值,即一段字符串是否包含几个单词。

例如,如果我要检查字符串是否存在串仅测试串 “的数据提供给测试只串”。

我已经编写了以下代码,但是无论字符串包含单词还是否,它都使我成真。

    private bool ContainsText(string input)
    {
        for (int i = 0; i < input.Length; i++)
        {
            if (((int)input[i] >= 65 && (int)input[i] <= 90) || ((int)input[i] >= 97 && (int)input[i] <= 177))
                return true;
        }

        return false;
    }

当我调用以下行时,我总是得到true ,这是不正确的

MessageBox.Show(ContainsText("test only string").ToString());

在代码方面,如果由于某种原因input 任何字符位于“ A到Z”或“ a到U + 00B1”中,您的ContainsText代码将立即返回true

但是问题还不止于此:您已经描述了两个输入-要检查的字符串(例如“仅测试字符串”)和要检查其存在的字符串(例如“提供数据以仅测试字符串”)。 您的方法仅接受一个输入,而不使用任何其他状态。 因此它不可能工作。 值得退后一步,尝试弄清为什么您没有注意到需要两个输入-以及为什么实际上您的测试仅使用“仅测试字符串”,却没有提及“提供数据以仅测试字符串”。

您实际上根本不需要任何方法- String已经具有一个Contains方法:

if (textToCheck.Contains(textToFind))
{
    ...
}

假设您要进行序数比较。 如果要以区分文化或不区分大小写的方式进行检查,请结合使用IndexOf和适当的StringComparison

一个简单的string.IndexOf可能带有枚举来忽略大小写:

 string myTestString = "Data is provided to Test Only String";
 if(myTestString.IndexOf("test only string", StringComparison.CurrentCultureIgnoreCase) >= 0)
    Console.WriteLine("Found text");

当然,字符串类也有一个Contains方法,但是它是作为对IndexOf的调用实现的,不可能忽略大小写。

public bool Contains(string value)
{
     return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}

您可以使用String对象的Contains方法。

var a = "Data is provided to test only string";
var b = "test only string";

if (a.Contains(b))
     MessageBox.Show("yes");

使用IndexOf

http://www.dotnetperls.com/indexof

使用示例

string str = "string to test";
bool result = str.IndexOf("The hosted network started.") != -1;

MessageBox.Show(result.ToString());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM