string text = "{hello|{hi}} {world}";
实际上我想要给定字符串中的'{'和'}'每个出现位置
请帮助我...提前谢谢!
您可以使用 Regex.Matches。它将搜索所有被“|”分割的字符串 在句子中。您可以将所有字符串及其索引添加到字典。
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-}
您可以使用正则表达式制作一个将遍历您的字符的函数
示例 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);
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
创建两个列表
List<int> opening
List<int> closing
然后扫描字符串中的 int i = 0; i < string.length -1;i++。将每个字符与左括号或右括号进行比较。就像 if chr == '{' 然后将计数器 i 放入相应的列表中。
在整个字符串之后,您应该在相应的列表中有位置开始和结束括号。
那有帮助吗?
您可以枚举出现的情况:
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, '{', '}')) {
...
}