Search code examples
c#visual-studioconcatenationstring-concatenation

Concatenating of Strings


I have task to implement method returning string.Contact(str1, str2, str3), but in the list of test cases i observe, that some of them have more than 3 input arguments (actually 4 and 5). I don't have idea, what algorithm i should write (because in msdn i didn't see anything similiar). Appreciate all help.

My sample :

   public static string ConcatenateStrings(string str1, string str2, string str3)
    {
        return string.Concat(str1 + str2 + str3);
    }

Code of TestCases :

 [TestCase("", "", "", ExpectedResult = "")]
    [TestCase("a", "b", "c", ExpectedResult = "abc")]
    [TestCase("abc", "bcd", "cde", ExpectedResult = "abcbcdcde")]
    public string ConcatenateStrings_ThreeParameters_ParametersAreValid_ReturnsResult(string str1, string str2, string str3)
    {
        // Act
        return ConcatenatingStrings.ConcatenateStrings(str1, str2, str3);
    }

    [TestCase("", "", "", "", ExpectedResult = "")]
    [TestCase("a", "b", "c", "d", ExpectedResult = "abcd")]
    [TestCase("abc", "bcd", "cde", "def", ExpectedResult = "abcbcdcdedef")]
    public string ConcatenateStrings_ThreeParameters_ParametersAreValid_ReturnsResult(string str1, string str2, string str3, string str4)
    {
        // Act
        return ConcatenatingStrings.ConcatenateStrings(str1, str2, str3, str4);
    }

Result of TestCases :

enter image description here


Solution

  • Using the params keyword, you can pass an array into your method.

    Reference https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

    public static string ConcatenateStrings(params string[] str)
    {
        string concat;
    
        foreach(string s in str)
        {
            concat = string.Concat(concat, s);
        }
    
        return concat;
    }