简体   繁体   中英

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

Can anyone help me in writing a piece of code in C# Winforms, which can give me a boolean value, that whether a piece of string contains a few words.

For example, If I want to check whether string test only string exists in string "Data is provided to test only string".

I have written following piece of code, but it alwys gives me true, whether string contains the words or nor.

    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;
    }

When I call the following line, I always get true , which is not correct

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

Code-wise, your ContainsText code immediately returns true if any character in input is either in "A to Z" or "a to U+00B1" for some reason.

But the problems lie deeper than that: you've described two inputs - the string to check for, eg "test only string" and the string to check for its presence, eg "Data is provided to test only string". Your method only accepts one input, and doesn't use any other state. So it can't possibly work. It's worth taking a step back and trying to work out why you didn't notice that you needed two inputs - and why indeed your test only used "test only string" and didn't mention "Data is provided to test only string".

You don't really need a method at all though - String already has a Contains method:

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

That's assuming you want an ordinal comparison. Use IndexOf with an appropriate StringComparison if you want to check in a culture-sensitive or case-insensitive way.

A simple string.IndexOf perhaps with the enum to ignore case:

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

Of course the string class has also a Contains method, but it is implemented as a call to IndexOf, without the possibility to ignore the case.

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

You can use Contains method of String object.

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

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

Use IndexOf

http://www.dotnetperls.com/indexof

example of usage..

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

MessageBox.Show(result.ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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