I'm trying to store unknown amount of specific strings inside a string but I want to get it's index so I can check it again. For example:
List<string> values = new List<string>();
int num;
string line = "/hello/1 /a/sdhdkd asjs /hello/2 ajhsd asjskjd skj /hello/s sajdk /hello/3 assdsfd hello/4";
And I want to store: /hello/1
, /hello/2
, /hello/3
and /hello/4
but NOT hello/s because it's different pattern (Not number) in a string List but I don't know how...
What I think is this:
//detect a common pattern between them
if(line.Contains("/hello/")
How can I know which is the position of the last "/" found in "/hello/" (In line
it would be line[6]
) so I can do this: if(int.TryParse(line[7], num))
if this TryParse returns true, it would store values.Add("/hello/"+line[7]);
The value after "/" won't be higher than 9 or negative (Example: /hello/34 or /hello/-23)
And then an auxiliar string would be what is AFTER this:
string aux = "";
for(int i=index_value; i<line.Length; i++) aux+= line[i]; //Where index_value would be 7+1
line = aux;
So now, line is:
" /a/sdhdkd asjs /hello/2 ajhsd asjskjd skj /hello/s sajdk /hello/3 assdsfd hello/4";
and I will make the search again, but what I am missing is how to get that index value so next time I make this search, my line would be:
" ajhsd asjskjd skj /hello/s sajdk /hello/3 assdsfd hello/4";
after finding and saving "/hello/2"
This looks like a good place to use regular expressions (and that's not something I say often). For example:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
var regex = new Regex(@"/hello/\d+\b");
var text = "/hello/1 /a/sdhdkd asjs /hello/2 ajhsd "
+ "asjskjd skj /hello/s sajdk /hello/3 assdsfd hello/4";
foreach (Match match in regex.Matches(text))
{
Console.WriteLine("{0} at {1}", match.Value, match.Index);
}
}
}
Output:
/hello/1 at 0
/hello/2 at 24
/hello/3 at 66
(No hello/4
, because it doesn't have a leading slash.)
If the hello
shouldn't be hardcoded, you could use new Regex(@"/\w+/\d+\b")
or something similar to allow all word characters in the slug.
See more on this question at Stackoverflow