Results 1 to 3 of 3

Thread: IndexOf

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2001
    Location
    Philadelphia
    Posts
    89

    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.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    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.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    type Woss is new Grumpy; wossname's Avatar
    Join Date
    Aug 2002
    Location
    #!/bin/bash
    Posts
    5,682

    Re: IndexOf

    Regex is complete overkill.

    if (mystring.indexof(" JHJH ") > -1)
    I don't live here any more.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width