Example:
string input = "super";
string rep = "a";
I want the output same charterers as per given input string
length
. The output should be " aaaaa
". I dont like to use own FOR or While loops logic, is there any alternatives to accomplish it.
Use the constructor
string output = new string('a', input.Length);
If you want to repeat a real string
n-times, you could use Enumerable.Repeat
:
string output = string.Join("", Enumerable.Repeat(rep, input.Length));
I use String.Join
to concatenate each string with a specified seperator(in this case none).
By Using Regular Expressions
string input = "123";
string rep = "Abc";
string output = Regex.Replace(input , "(.)", rep)
By using LINQ
string output = string.Concat(input.Select(c => rep));
Output
AbcAbcAbc
只是为了好玩,这是另一种方式:
new string(input.Select(c => 'a').ToArray());
another way :
string input = "super";
string rep = "a";
var newStr = input.Select(x => rep);
Of if you want a solution that's way to big but very easy to understand:
string output = "";
foreach(char a in input) { // == for(int i = 0; i < input.length; i++) {
output += rep;
}
I didn't know about working with the constructor.
It's a very easy solution, but it'll only work with char's. So you can't repeat strings.
string op = "";
for(int i = 0; i < input.Length; i++)
op += rep;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.