【问题标题】:Replace some letters of string with specific symbol [duplicate]用特定符号替换字符串的一些字母[重复]
【发布时间】:2016-07-24 03:52:51
【问题描述】:

我有一个这样的字符串:

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 *, 

我该怎么做?

【问题讨论】:

  • 为什么clearIndexesList&lt;string&gt; 而不是List&lt;int&gt;

标签: c# string


【解决方案1】:

这是一种需要List&lt;string&gt; 索引的方法

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*

【讨论】:

  • 感谢您的回复,但 clearIndexes 是字符串列表,我无法更改它的类型,因此出现错误。
  • @someone,为什么是List&lt;string&gt; 以及为什么不加星标的字符位置不是索引(而是index + 1)?
  • new string(word.Select((c, i) =&gt; !clearIndexes.Contains(i+1) ? '*' : c).ToArray()); 稍微好一点,以避免将每个 char 转换为 string
  • @Sinatr 这些索引是通过 linq 查询操作的:data.Where(s => s.StartsWith(Word)).Where(s => !s.EndsWith("X") ).Select(s=>s.Remove(0,Word.Length)) 结果是字符串列表
【解决方案2】:

可以使用以下代码-sn-p:

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();

【讨论】:

    【解决方案3】:

    您还可以使用简单的for-loop 并操作由ToCharArray 返回的char[]

    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&lt;int&gt; 并存储从零开始的索引。

    【讨论】:

      猜你喜欢
      • 2017-03-02
      • 2020-04-13
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2019-10-14
      相关资源
      最近更新 更多