循环遍历字符串以查找子字符串

Den*_*ena 1 c# string

我有这个字符串:

text = "book//title//page/section/para";
Run Code Online (Sandbox Code Playgroud)

我想通过它来查找所有//和/和它们的索引.

我尝试这样做:

if (text.Contains("//"))
{
    Console.WriteLine(" // index:  {0}  ", text.IndexOf("//"));   
}
if (text.Contains("/"))
{
    Console.WriteLine("/ index:  {0}  :", text.IndexOf("/"));    
}
Run Code Online (Sandbox Code Playgroud)

我也在考虑使用:

Foreach(char c in text)
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为//不是一个单一的char.

我怎样才能实现我的目标?

我也尝试了这个,但没有显示结果

string input = "book//title//page/section/para"; 
string pattern = @"\/\//";


Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
 if (matches.Count > 0)
  {
      Console.WriteLine("{0} ({1} matches):", input, matches.Count);
      foreach (Match match in matches)
         Console.WriteLine("   " + input.IndexOf(match.Value));
 }
Run Code Online (Sandbox Code Playgroud)

先感谢您.

Tim*_*mwi 9

简单:

var text = "book//title//page/section/para";
foreach (Match m in Regex.Matches(text, "//?"))
    Console.WriteLine(string.Format("Found {0} at index {1}.", m.Value, m.Index));
Run Code Online (Sandbox Code Playgroud)

输出:

Found // at index 4.
Found // at index 11.
Found / at index 17.
Found / at index 25.
Run Code Online (Sandbox Code Playgroud)