1

I want to create a function that takes a list of strings as a parameter, joins them together into a single string with each element separated by a comma, and returns the result. For example, if the array [“asdf”, “jkl”, “zxc”] is passed into the function, it will return a string “asdf, jkl, zxc”.

In C#, my function signature look like this:

string MySolution(string[] inputStrings)

{
  List<string> cities = new List<string>();
        cities.Add("New York");
        cities.Add("Mumbai");
        cities.Add("Berlin");
        cities.Add("Istanbul");

        string line = string.Join(",", cities.ToArray());
        Console.WriteLine(line);
}

--I'm just having problems when it comes to having a user input where in a user will enter values, not the static as shown in the code. I will appreciate any suggestions or answers with regards to that. This also reserves as a test in the company that I'm applying for.

doria_aries
  • 77
  • 1
  • 1
  • 10
  • 3
    Are you looking for `string.Join`? e.g. `return string.Join(", ", inputStrings);` – Dmitry Bychenko Jun 08 '18 at 08:43
  • Yes. I want to create a function that takes a list of string as a parameter and it must work for any array passed into it – doria_aries Jun 08 '18 at 08:45
  • @Aries that's what `String.Join` does. You don't need to create a new one. Check [its source code](https://referencesource.microsoft.com/#mscorlib/system/string.cs,84) to see how it handles any collection or variable argument lists – Panagiotis Kanavos Jun 08 '18 at 08:50
  • *Currying* the method though is very useful. You could create your own eg JoinComma as `public static string JoinComma(IEnumerable items)=>String.Join(",",items);` or using a local functions `string commaJoins(IEnumerable items)=>String.Joins(",",items);`. Or you could use similar syntax to create a `Func,string> commaJoiner= items=>String.Join(",",items);` Or – Panagiotis Kanavos Jun 08 '18 at 09:03
  • @Aries you can generalize this by creating a function that takes a separator and returns a `Func,string> curryJoiner(string sep){ Func,string> myJoiner= items=>String.Join(sep,items); return myJoiner;}` – Panagiotis Kanavos Jun 08 '18 at 09:05

1 Answers1

3

You don't need a method. You've already got:

string myJoinedString = String.Join(",", myStrings);

MSDN reference

There is no reason to wrap String.Join in a method here. The additional layer is nothing but a hollow wrapper. Unless you want to start adding additional logic (error handling, custom separator logic, ...), but that's not part of your current question.

Flater
  • 12,908
  • 4
  • 39
  • 62