Hurrem
Hurrem

Reputation: 183

String.Equals how does it work?

I have string text="camel", and then I want to check if text contains letter "m", so I loop through it and checking it using:

if (text[i].Equals("m"))

but this never returns me true... why?

Upvotes: 1

Views: 210

Answers (5)

Tacit
Tacit

Reputation: 908

The answers has been given to you by Kyle C, so this is how you complete the whole process and I'm gonna use winforms as an example:

private void button1_Click(object sender, EventArgs e)
{
    string text = "camel";

    if (text.Contains("m") || text.Contains("M"))//also checks for capital M
    {
        MessageBox.Show("True");
    }
}

Upvotes: 0

Tim Lehner
Tim Lehner

Reputation: 15251

As mentioned by @MattGreer, you're currently comparing a character and a string. This is because of the delimiter you've chosen for your literal, and because text[i] returns a character from a string rather than a substring of that string.

Please note the difference between using string literal delimiters (quote) and character literal delimiters (apostrophe):

if (text[i].Equals('m'))

Also, as others have stated, unless there is some reason you want to iterate through each character, String.Contains() would seemingly serve the intended purpose.

Upvotes: 2

Casperah
Casperah

Reputation: 4554

You need to find all occurences of a letter in a text as I understand it:

string text = "camel";
string lookup = "M";
int index = 0;
while ( (index = text.IndexOf(lookup, index, StringComparison.OrdinalIgnoreCase) != -1)
{
   // You have found what you looked for at position "index".

}

I don't think that you get it any faster than this.

Good luck with your quest.

Upvotes: 0

Kyle C
Kyle C

Reputation: 1637

Since you are comparing a character with a string this won't work. Here's some more information on String comparisons

In this case you should use

if(text.Contains("m"))

Upvotes: 3

plast1K
plast1K

Reputation: 469

Miraclessss

Use Contains

You're asking if "camel" is the equivalent of "m" -- which it is not.

"camel" contains "m".

Upvotes: -2

Related Questions