如何在给定字符串中查找多次出现的空格字符
本文关键字:字符 空格 查找 字符串 | 更新日期: 2023-09-27 18:27:00
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-}
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
你可以使用正则表达式来制作一个函数,该函数将循环遍历你的字符
例 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);
创建两个列表 List<int> opening
List<int> closing
然后扫描字符串以查找 int i = 0; 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, '{', '}')) {
...
}