You have to use code like this.
int index = s.IndexOf(',', s.IndexOf(',') + 1);
You may need to make sure you do not go outside the bounds of the string though. I will leave that part up to you.
Domanda
I have a string in an Array that contains two commas as well as tabs and white spaces. I'm trying to cut two words in that string, both of them before the commas, I really don't care about the tabs and white spaces.
My String looks similar to this:
String s = "Address1 Chicago, IL Address2 Detroit, MI"
I get the index of the first comma
int x = s.IndexOf(',');
And from there, I cut the string before the index of the first comma.
firstCity = s.Substring(x-10, x).Trim() //trim white spaces before the letter C;
So, how do I get the index of the second comma so I can get my second string?
I really appreciate your help!
Soluzione
You have to use code like this.
int index = s.IndexOf(',', s.IndexOf(',') + 1);
You may need to make sure you do not go outside the bounds of the string though. I will leave that part up to you.
Altri suggerimenti
I just wrote this Extension method, so you can get the nth index of any sub-string in a string.
Note: To get the index of the first instance, use nth = 0
.
public static class Extensions
{
public static int IndexOfNth(this string str, string value, int nth = 0)
{
if (nth < 0)
throw new ArgumentException("Can not find a negative index of substring in string. Must start with 0");
int offset = str.IndexOf(value);
for (int i = 0; i < nth; i++)
{
if (offset == -1) return -1;
offset = str.IndexOf(value, offset + 1);
}
return offset;
}
}
LastIndexOf gives you the Index of the last occurence of the given char / string.
int index = s.LastIndexOf(',');