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?
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")) Equals checks whatever the developer defined it to mean in the Equals method of the type. If not overridden it compares the references for classes and the bytes of all fields for structs. operator == does whatever the user defined operator tells it to do, unless there is no user defined operator in which case it compares the references for classes and the bytes of all fields for structs. So the two concepts are exactly the same except that developers can define each method differently.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.
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.
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"); } }
text[i]is a char, which will never equal a string. You can just dotext[i] == 'm'