-
IndexOf
Hi,
ran into a problem, taking the whole afternoon trying to figure it out.
I have string "JHJH KWIW KWJEJ WNDSJ DS SDS"
I'm appending spaces in the beginning and the end of the string, just to make sure that I grab out specific string, I need to find a specific string, some things inside could have the smae ending or beginning. So I'm doing mystring = " "+mystring+" ";
if (mystring.indexof(" JHJH ") > 0)
return "trata"
now if JHJH is inside the string second or third doesn't matter, but if it is first it is not going to be found unless I remove the leading space "JHJH " It seems that PadLeft or " "+mystring irregardless of the case will remove the elading space. Does anyone have any insight into this. Any input will be greatly appreciated.
-
Re: IndexOf
You should use a regular expression. It can be told to search for a whole word only, which will include anything from the beginning of the string to a space, anything from a space to a space and anything from a space to the end of the string. There are tutorials on regular expression syntax in my signature and they are implemented in .NET through the System.Text.RegularExpressions namespace and particularly the Regex class. I'm no expert on the subject but I believe that this will do the job:
Code:
string str = "JHJH KWIW KWJHJHJEJ WNDSJ DS SDS";
Regex rgx = new Regex(@"\bJHJH\b");
MatchCollection mtchs = rgx.Matches(str);
foreach (Match mtch in mtchs)
{
MessageBox.Show("Match found at index " + mtch.Index.ToString());
}
The "\b" indocates the beginning or the end of a word, so places where "JHJH" forms part of a larger word will not match.
-
Re: IndexOf
Regex is complete overkill.
if (mystring.indexof(" JHJH ") > -1)