patterncsharpModerate
A method which, given a string, returns a string in which each character is separated by an asterisk
Viewed 0 times
eachmethodgivencharacterseparatedreturnswhichstringasterisk
Problem
Use recursion in the solution.
I would really appreciate if you can help me to find a better way to do it.
I would really appreciate if you can help me to find a better way to do it.
public class AppendCharacterAfterEachCharacterInString
{
int index =0;
StringBuilder outputString = new StringBuilder();
public string AppendInputCharacterAfterEachCharacterInString(string sInputString, string inputRepeatCharacter)
{
if (string.IsNullOrEmpty(sInputString))
{
Console.WriteLine("Empty string !");
}
else
{
BuildNewString(sInputString, inputRepeatCharacter);
}
return outputString.ToString();
}
private void BuildNewString(string inputString, string repeatCharacter)
{
if (index < inputString.Length)
{
outputString.Append(inputString[index]);
if(!(inputString[index].ToString().Trim() == string.Empty) && !(index + 1 == inputString.Length))
outputString.Append(repeatCharacter);
index++;
BuildNewString(inputString, repeatCharacter);
}
}Solution
Well, you've used recursion, but I wouldn't say that's a recursive solution because you have variables outside your functions that control what your functions do.
A recursive solution will have a function that is repeatedly called with smaller and smaller sub-problems, terminating in a base case, that together will accomplish your goal. A key aspect of recursive solutions is that the recursive function returns a value - your method is
As a first step, discard your
A recursive solution will have a function that is repeatedly called with smaller and smaller sub-problems, terminating in a base case, that together will accomplish your goal. A key aspect of recursive solutions is that the recursive function returns a value - your method is
void and so returns no value.As a first step, discard your
index variable entirely. At each recursive step, call BuildNewString with a smaller version of the same problem. Combine the results in such a way as to produce the desired result.Context
StackExchange Code Review Q#51359, answer score: 10
Revisions (0)
No revisions yet.