Refactor Code

  • Gravatar
    Convert String Array to Separator String

    by azamsharp on 7/24/2008 9:16:29 AM
  • Here is a small piece of code that converts a string array to a separated string. The separator can be a comma, space etc.
  • // create a string out of an array
    private static string GetSeparatedStringFromArray(string[] source, string separator)
    {
    StringBuilder sb = new StringBuilder();

    foreach (string str in source)
    {
    sb.Append(str);
    sb.Append(separator);
    }

    return sb.ToString().TrimEnd(separator);
    }
  • Refactor it!
  • Gravatar
    I think this one is much better! Now, the separator is char instead of a string. You can go one step forward and provide char[] instead of a single char.
    by azamsharp on 7/24/2008 9:22:26 AM
  • // create a string out of an array
    private static string GetSeparatedStringFromArray(string[] source, char separator)
    {
    StringBuilder sb = new StringBuilder();

    foreach (string str in source)
    {
    sb.Append(str);
    sb.Append(separator);
    }

    return sb.ToString().TrimEnd(separator);
    }
  • Gravatar
    Am I missing something? What's wrong with the following?
    by MrBretticus on 7/24/2008 11:45:13 PM
  • String.Join(",", new string[] { "Item 1", "Item 2" });
  • Gravatar
    Nice MrBretticus, I completely forgot about the String.Join method. Thanks for reminding me!
    by azamsharp on 7/25/2008 6:34:58 AM
  • String.Join(",", new string[] { "Item 1", "Item 2" });
Please log in to refactor the code! Login