patterncsharpMinor
Given a string, return a string where every character in the original is doubled
Viewed 0 times
doubledthereturnoriginalwheregiveneverycharacterstring
Problem
For example, given the string "xyz", return the string "xxyyzz".
I was given this as a part of a test. I would really appreciate if you can help me to find a better way of doing it.
I came up with two methods to do the same thing but one was an extension method.
I have a couple more questions which I will post in separate posts.
I was given this as a part of a test. I would really appreciate if you can help me to find a better way of doing it.
I came up with two methods to do the same thing but one was an extension method.
I have a couple more questions which I will post in separate posts.
public class RepeatCharactersInString
{
public string RepeatAString(string sInputString, int repeatCount)
{
StringBuilder sOutputString = new StringBuilder();
if (string.IsNullOrEmpty(sInputString))
{
Console.WriteLine("Empty string !");
}
else
{
foreach (char c in sInputString)
{
sOutputString.Append(new String(c, repeatCount));
}
}
return sOutputString.ToString();
}
}
// Method 2 Using extension methods
public static class RepeatCharactersInStingExtensions
{
public static string RepeatAllCharactersInThisString(this string sInputString, int repeatCount)
{
StringBuilder sOutputString = new StringBuilder();
if (string.IsNullOrEmpty(sInputString))
{
Console.WriteLine("Empty string !");
}
else
{
foreach (char c in sInputString)
{
sOutputString.Append(new String(c, repeatCount));
}
}
return sOutputString.ToString();
}
}Solution
No reason to write anything when string is empty.
I think your solution is the best. Obviously you can use LINQ if you want but IMO it doesn't bring anything to table.
public string RepeatAString(string sInputString, int repeatCount)
{
StringBuilder sOutputString = new StringBuilder();
foreach (char c in sInputString)
sOutputString.Append(new String(c, repeatCount));
return sOutputString.ToString();
}I think your solution is the best. Obviously you can use LINQ if you want but IMO it doesn't bring anything to table.
public string RepeatAString(string input, int count)
{
return String.Concat(input.Select(c => new String(c, count)));
}Code Snippets
public string RepeatAString(string sInputString, int repeatCount)
{
StringBuilder sOutputString = new StringBuilder();
foreach (char c in sInputString)
sOutputString.Append(new String(c, repeatCount));
return sOutputString.ToString();
}public string RepeatAString(string input, int count)
{
return String.Concat(input.Select(c => new String(c, count)));
}Context
StackExchange Code Review Q#51354, answer score: 3
Revisions (0)
No revisions yet.