我有一个int(openStartParenthesisIndex
)字典,其中包含字符串中所有括号的索引(键为closeEndParenthesisIndex
,值为stringX.stringY(())() -> stringX.stringY$($()^)^$()^
$ = openParenthesisStartIndex
^ = closeParenthesisEndIndex
)
例如在文本中
key value
(openParenthesisStartIndex) --- (closeParenthesisEndIndex)
item1 15 19
item2 16 18
item3 19 21
字典项目:
string myText = "stringX.stringY(())()";
Dictionary<int, int> myIndexs = new Dictionary<int, int>();
foreach (var x in myIndexs)
{
myText = myText.Remove(item.Key, 1).Remove(item.Value-1);
}
我的问题是当我循环我的字典并尝试在字符串中删除它时,下一个循环索引无效,因为它已经更改,因为我将其删除。
{{1}}
问题:如何删除字符串中的所有索引(从startIndex [key]到endIndex [value])?
答案 0 :(得分:1)
为了防止索引发生变化,一个技巧就是从结尾开始删除出现的事件:
string myText = stringX.stringY(())();
Dictionary<int, int> myIndexs = new Dictionary<int, int>();
var allIndexes = myIndexs.Keys.Concat(myIndexs.Values);
foreach (var index in allIndexes.OrderByDescending(i => i))
{
myText = myText.Remove(index, 1);
}
请注意,您可能根本不需要字典。考虑用列表替换它。
答案 1 :(得分:0)
StringBuilder
将更适合您的情况。 StringBuilder MSDN
按降序排序键也可以删除所有索引。
另一种解决方法可能是将中间字符放在所需的索引处,并最终替换该字符的所有实例。
StringBuilder ab = new StringBuilder("ab(cd)");
ab.Remove(2, 1);
ab.Insert(2, "`");
ab.Remove(5, 1);
ab.Insert(5, "`");
ab.Replace("`", "");
System.Console.Write(ab);
答案 2 :(得分:0)
当您对字符串进行更改时,字符串始终会创建一个新字符串,因此您需要创建一个没有删除部分的新字符串。这段代码有点复杂,因为它处理潜在的重叠。也许更好的方法是清理索引,制作一个索引列表,以正确的顺序表示相同的删除而不重叠。
public static string removeAtIndexes(string source)
{
var indexes = new Tuple<int, int>[]
{
new Tuple<int, int>(15, 19),
new Tuple<int, int>(16, 18),
new Tuple<int, int>(19, 21)
};
var sb = new StringBuilder();
var last = 0;
bool copying = true;
for (var i = 0; i < source.Length; i++)
{
var end = false;
foreach (var index in indexes)
{
if (copying)
{
if (index.Item1 <= i)
{
copying = false;
break;
}
}
else
{
if (index.Item2 < i)
{
end = true;
}
}
}
if (false == copying && end)
{
copying = true;
}
if(copying)
{
sb.Append(source[i]);
}
}
return sb.ToString();
}