0

I have a String I want to get the index of the "id:" i.e the id along with the double quotes.

How I am supposed to do so inside C# string.IndexOf function?

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164

4 Answers4

5

This will get the index of the string you want:

var idx = input.IndexOf("\"id:\"");

if you wanted to pull it out you'd do something like this maybe:

var idx = input.IndexOf("\"id:\"");
var val = input.Substring(idx, len);

where len is either a statically known length or also calculated by another IndexOf statement.

Honestly, this could also be done with a Regex, and if an example were available a Regex may be the right approach because you're presumably trying to get the actual value here and it's presumably JSON you're reading.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
3

" is an escape sequence

If you want to use a double quotation mark in your string, you should use \" instead.

For example;

int index = yourstring.IndexOf("\"id:\"");

Remember, String.IndexOf method gets zero-based index of the first occurrence of the your string.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
  • 1
    @user3136399 You are quite welcome. If one of these answer solve your problem, please consider to accept one http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Soner Gönül Dec 31 '13 at 14:51
3

This is a simple approach: If you know double quote is before the Id then take index of id - 1?

string myString = @"String with ""id:"" in it";
var indexOfId = myString.IndexOf("id:") - 1;

Console.WriteLine(@"Index of ""id:"" is {0}", indexOfId);
Kaf
  • 33,101
  • 7
  • 58
  • 78
0

Reading between the lines, if this is a JSON string, and you have .NET 4 or higher available, you can ask .NET to deserialize the string for you rather than parsing by hand: see this answer.

Alternatively you might consider Json.NET if you're working very heavily with JSON.

Otherwise, as others note, you need to escape the quotes, so for example:

text.IndexOf("\"id:\"")
text.IndexOf(@"""id:""")

or for overengineered legiblity:

string Quoted(string text)
{
    return "\"" + text + "\""; // generates unnecessary garbage
}

text.IndexOf(Quoted("id:"))
Community
  • 1
  • 1
El Zorko
  • 3,349
  • 2
  • 26
  • 34