Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending Strings in Java/C# without using StringBuffer.Append or StringBuilder.Append

Tags:

java

c#

at a recent interview I attended, the programming question that was asked was this. Write a function that will take as input two strings. The output should be the result of concatenation.

Conditions: Should not use StringBuffer.Append or StringBuilder.Append or string objects for concatenation;that is, they want me to implement the pseudo code implementation of How StringBuilder or StringBuffer's Append function works.

This is what I did:

    static char[] AppendStrings(string input, string append)
    {
        char[] inputCharArray = input.ToCharArray();
        char[] appendCharArray = append.ToCharArray();
        char[] outputCharArray = new char[inputCharArray.Length + appendCharArray.Length];
        for (int i = 0; i < inputCharArray.Length; i++)
        {
            outputCharArray[i] = inputCharArray[i];
        }
        for (int i = 0; i < appendCharArray.Length; i++)
        {
            outputCharArray[input.Length + i] = appendCharArray[i];
        }
        return outputCharArray;
    }

While this is a working solution, is there a better way of doing things?

like image 910
Magic Avatar asked Dec 27 '22 22:12

Magic


1 Answers

is LINQ legal? strings are just can be treated as an enumeration of chars, so they can be used with LINQ (even though there is some cost involved, see comments):

string a = "foo";
string b = "bar";

string c = new string(a.AsEnumerable().Concat(b).ToArray());

or with your method signature:

 static char[] AppendStrings(string input, string append)
 {
   return input.AsEnumerable().Concat(append).ToArray();
 }
like image 61
BrokenGlass Avatar answered Jan 22 '23 20:01

BrokenGlass