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?
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?
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.
"
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.
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);
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:"))