0

I am really a beginner, I already know

string.indexOf("");

Can search for a whole word, but when I tried to search for e.g: ig out of pig, it doesn't work.

I have a similar string here(part of):

<Special!>The moon is crashing to the Earth!</Special!>

Because I have a lot of these in my file and I just cannot edited all of them and add a space like:

< Special! > The moon is crashing to the Earth! </ Special! > 

I need to get the sub-string of Special! and The moon is crashing to the Earth! What is the simple way to search for a part of a word without adding plugins like HTMLAgilityPack?

1
  • 2
    IndexOf... You just most probably using it wrong, what have you tried? Commented Jan 20, 2013 at 1:36

4 Answers 4

1

IndexOf will work, you are probably just using it improperly.

If your string is in a variable call mystring you would say mystring.IndexOf and then pass in the string you are looking for.

string mystring = "somestring";
int position = mystring.IndexOf("st");
Sign up to request clarification or add additional context in comments.

Comments

0

How are you using it? You should use like this:

string test = "pig";
int result = test.IndexOf("ig");
// result = 1

If you want to make it case insensitive use

string test = "PIG";
int result = test.IndexOf("ig", StringComparison.InvariantCultureIgnoreCase);
// result = 1

Comments

0

Please try this:

string s = "<Special!>The moon is crashing to the Earth!</Special!>";
int whereMyStringStarts = s.IndexOf("moon is crashing"); 

IndexOf should work with spaces too, but maybe you have new line or tab characters, not spaces?

Sometimes case-sensitivity is important. You may control it by additional parameter called comparisonType. Example:

 int whereMyStringStarts = s.IndexOf("Special", StringComparison.OrdinalIgnoreCase);

More information about IndexOf: String.IndexOf Method at MSDN

Anyway, I think you may need regular expressions to create better parser. IndexOf is very primitive method and you may stuck in big mess of code.

Comments

0
   string page = "<Special!>The moon is crashing to the Earth!</Special!>";
        if (page.Contains("</Special!>"))
        {
            pos = page.IndexOf("<Special!>");
            propertyAddress = page.Substring(10, page.IndexOf("</Special!>")-11);
            //i used 10 because <special!> is 10 chars, i used 11 because </special!> is 11
        }

This will give you "the moon is crashing to the earth!"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.