How to replace whole characters in a string with identical characters in C #?

Example:

string input = "super"; string rep = "a"; 

I want the same charterers to exit according to the given input string length . The output should be " aaaaa ". I do not like to use my own FOR or While Loops logic, are there any alternatives for its implementation.

+6
source share
6 answers

Using regular expressions

 string input = "123"; string rep = "Abc"; string output = Regex.Replace(input , "(.)", rep) 

Using LINQ

 string output = string.Concat(input.Select(c => rep)); 

Output

Abcabcabc

+7
source

Use constructor

 string output = new string('a', input.Length); 

If you want to repeat the real string n times, you can use Enumerable.Repeat :

 string output = string.Join("", Enumerable.Repeat(rep, input.Length)); 

I use String.Join to concatenate each line with the specified delimiter (in this case, no).

+27
source

Just for fun, here is another way:

 new string(input.Select(c => 'a').ToArray()); 
+3
source

another way:

 string input = "super"; string rep = "a"; var newStr = input.Select(x => rep); 
0
source

If you want the solution to be so big, but very easy to understand:

 string output = ""; foreach(char a in input) { // == for(int i = 0; i < input.length; i++) { output += rep; } 

I did not know about working with the designer.
This is a very simple solution, but it will only work with char. Therefore, you cannot repeat lines.

0
source
 string op = ""; for(int i = 0; i < input.Length; i++) op += rep; 
0
source

Source: https://habr.com/ru/post/946308/


All Articles