0

i have a string like this:

string word="HELLO";

and clear indexes of string like this:

IList<string> clearIndexes = indexes;// for example {2,4}

what i want is

 *E*L*// the 2th and 4th elements are clear and the other should be shown with *, 

how can I do that?

someone
  • 535
  • 4
  • 14

3 Answers3

5

here is one approach with the required List<string> of indexes

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

usually a index starts at 0 so i added (i+1) to get the result *E*L*

fubo
  • 44,811
  • 17
  • 103
  • 137
  • thanx for your response but clearIndexes are list of strings and I cant change the type of it, so I get error. – someone Apr 04 '16 at 14:41
  • @someone, why is it `List` and why position of character to leave un-starred is not index (but `index + 1`) ? – Sinatr Apr 04 '16 at 14:42
  • Slightly better would be `new string(word.Select((c, i) => !clearIndexes.Contains(i+1) ? '*' : c).ToArray());` to avoid converting each `char` to a `string`. – juharr Apr 04 '16 at 14:44
  • @Sinatr these indexes are manipulated with a linq query of this: data.Where(s => s.StartsWith(Word)).Where(s => !s.EndsWith("X")).Select(s=>s.Remove(0,Word.Length)) and the result is list of strings – someone Apr 04 '16 at 14:45
0

You can use the following code-snippet:

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();
DmitryG
  • 17,677
  • 1
  • 30
  • 53
0

You could also use a simple for-loop and manipulate the char[] returned by 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);

In general it would be better to use a List<int> and to store the index which is zero based.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939