我有一个这样的字符串:
string word="HELLO";
并清除字符串索引,如下所示:
IList<string> clearIndexes = indexes;// for example {2,4}
我想要的是
*E*L*// the 2th and 4th elements are clear and the other should be shown with *,
我该怎么做?
答案 0 :(得分:5)
这是一种方法,其中包含所需的List<string>
索引
string word = "HELLO";
List<string> clearIndexes = new List<string> { "2", "4" };
string result = new string(word.Select((c, i) => !clearIndexes.Contains((i+1).ToString()) ? '*' : c).ToArray());
通常索引从0
开始,所以我添加了(i+1)
来获取结果*E*L*
答案 1 :(得分:0)
您可以使用以下代码段:
string word = "HELLO";
string[] strIndexes = new string[] { "2", "4" };
//
int[] replacementPositions = Enumerable.Range(1, word.Length) // nonzero-based
.Where(i => Array.IndexOf(strIndexes, i.ToString()) == -1)
.ToArray();
StringBuilder sb = new StringBuilder(word);
for(int i = 0; i < replacementPositions.Length; i++)
sb[replacementPositions[i] - 1] = '*';
string result = sb.ToString();
答案 2 :(得分:0)
您还可以使用简单的for
循环并操纵char[]
返回的ToCharArray
:
char[] chars = word.ToCharArray();
for (int i = 0; i < chars.Length; i++)
chars[i] = clearIndexes.Contains((i+1).ToString()) ? chars[i] : '*';
word = new string(chars);
一般情况下,最好使用List<int>
并存储基于零的索引。