перебрать строку, чтобы найти подстроку - PullRequest
1 голос
/ 19 января 2011

У меня есть эта строка:

text = "book//title//page/section/para";

Я хочу пройти через нее, чтобы найти все // и / и их индекс.

Я попытался сделать это с:

if (text.Contains("//"))
{
    Console.WriteLine(" // index:  {0}  ", text.IndexOf("//"));   
}
if (text.Contains("/"))
{
    Console.WriteLine("/ index:  {0}  :", text.IndexOf("/"));    
}

Я также думал об использовании:

Foreach(char c in text)

, но это не сработает, поскольку // - это не один символ.

Как мне добиться того, чего я хочу?

Я тоже пробовал это, но не показал результат

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));
 }

Заранее спасибо.

Ответы [ 5 ]

8 голосов
/ 19 января 2011

Simple:

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));

Выход:

Found // at index 4.
Found // at index 11.
Found / at index 17.
Found / at index 25.
3 голосов
/ 19 января 2011

Будет ли возможно использование Split?

Итак:

string[] words = text.Split(@'/');

А потом пройти через слова? Из-за // у вас будут пробелы, но это возможно?

2 голосов
/ 19 января 2011

Если вам нужен список "книга", "заголовок", "страница", "раздел", "пункт" Вы можете использовать сплит.

    string text = "book//title//page/section/para";
    string[] delimiters = { "//", "/" };

    string[] result = text.Split(delimiters,StringSplitOptions.RemoveEmptyEntries);
    System.Diagnostics.Debug.WriteLine(result);
    Assert.IsTrue(result[0].isEqual("book"));
    Assert.IsTrue(result[1].isEqual("title"));
    Assert.IsTrue(result[2].isEqual("page"));
    Assert.IsTrue(result[3].isEqual("section"));
    Assert.IsTrue(result[4].isEqual("para"));
1 голос
/ 19 января 2011

Sometin вроде:

bool lastCharASlash = false;
foreach(char c in text)
{
    if(c == @'/')
    {
      if(lastCharASlash)
      { 

          // my code...
      }
      lastCharASlash = true;
    }
    else lastCharASlash = false;
}

Вы также можете сделать text.Split(@"//")

0 голосов
/ 19 января 2011

Вы можете заменить // и / своими словами и затем найти последний индекс

string s = "book//title//page/section/para";

        s = s.Replace("//", "DOUBLE");
        s = s.Replace("/", "SINGLE");

        IList<int> doubleIndex = new List<int>();

        while (s.Contains("DOUBLE"))
        {
            int index = s.IndexOf("DOUBLE");
            s = s.Remove(index, 6);
            s = s.Insert(index, "//");
            doubleIndex.Add(index);
        }

        IList<int> singleIndex = new List<int>();

        while (s.Contains("SINGLE"))
        {
            int index = s.IndexOf("SINGLE");
            s = s.Remove(index, 6);
            s = s.Insert(index, "/");
            singleIndex.Add(index);
        }

Не забудьте сначала заменить double, в противном случае вы получите SINGLESINGLE для // вместо DOUBLE.Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...