1
string text = "{hello|{hi}} {world}";

実際には、指定された文字列から「{」と「}」の各出現位置が必要です

助けてください...よろしくお願いします!

4

5 に答える 5

3

Regex.Matches を使用できます。「|」で区切られたすべての文字列を検索します。文中。すべての文字列をインデックスとともに Dictioanry に追加できます。

  string pattern = "{|}";
  string text = "{hello|{hi}} {world}";
  Dictionary<int, string> indeces = new Dictionary<int, string>();
  foreach (Match match in Regex.Matches(text, pattern))
  {
       indeces.Add(match.Index, match.Value);
  }

結果は次のとおりです。

0-{
7-{
10-}
11-}
13-{
19-}
于 2013-08-08T05:50:07.090 に答える
2

文字をループする関数を作成する正規表現を使用できます

例 1

string text = "{hello|{hi}} {world}";
var indexes = new List<int>();
var ItemRegex = new Regex("[{}]", RegexOptions.Compiled);
foreach (Match ItemMatch in ItemRegex.Matches(text))
{
    indexes.Add(ItemMatch.Index);
}

例 2 (linq の方法)

string text = "{hello|{hi}} {world}";

var itemRegex = new Regex("[{}]", RegexOptions.Compiled);
var matches = itemRegex.Matches(text).Cast<Match>();
var indexes = matches.Select(i => i.Index);
于 2013-08-08T05:58:52.803 に答える
2
var str = "{hello|{hi}} {world}";
var indexes = str.ToCharArray()
             .Select((x,index) => new {x, index})
             .Where(i => i.x=='{' ||i.x=='}')
             .Select(p=>p.index);

結果

0 
7 
10 
11 
13 
19 
于 2013-08-08T05:52:03.347 に答える
1

2 つのリストを作成する List<int> opening List<int> closing

次に、文字列をスキャンして int i = 0; を探します。i < string.length -1;i++. 各文字を開き括弧または閉じ括弧と比較します。if chr == '{' のように、カウンター i を対応するリストに入れます。

文字列全体の後 対応するリストに、開き括弧と閉じ括弧の位置が必要です。

それは役に立ちましたか?

于 2013-08-08T05:52:49.483 に答える
0

発生を列挙できます。

public static IEnumerable<int> FindOccurences(String value, params Char[] toFind) {
  if ((!String.IsNullOrEmpty(value)) && (!Object.ReferenceEquals(null, toFind)))       
    for (int i = 0; i < value.Length; ++i) 
      if (toFind.Contains(value[i]))
        yield return i;
}

...

String text = "{hello|{hi}} {world}";

foreach(int index in FindOccurences(text, '{', '}')) {
  ...
}
于 2013-08-08T05:58:13.707 に答える