8 Replies - 500 Views - Last Post: 04 September 2018 - 04:39 AM

#1 andrewsw   User is offline

  • Unprocessable Entity
  • member icon

Reputation: 6595
  • View blog
  • Posts: 26,836
  • Joined: 12-December 12

neat comma removal

Posted 03 September 2018 - 07:47 AM

Not a big challenge, but I'm curious about how you might approach this.

I have three strings, say names1, names2 and names3 (not their actual names!).

names1 = "bob,ted,fred"
names2 = "mary,dave"
names3 = ""

Any one of them, or more, could be empty.

result = names1 + "," + names2 + "," + names3

This is no good because I'll easily end up with spare commas ,,

Would you stick with result and just remove any consecutive commas? But there could still be a spare one at the end that needs to be stripped.

Or concat them in three steps, checking what we have each time?

Is This A Good Question/Topic? 0
  • +

Replies To: neat comma removal

#2 andrewsw   User is offline

  • Unprocessable Entity
  • member icon

Reputation: 6595
  • View blog
  • Posts: 26,836
  • Joined: 12-December 12

Re: neat comma removal

Posted 03 September 2018 - 07:54 AM

Well, to use their real names (focussed, fundamentals and macros) I've just written this ugly code:

            // collate all 3
            string altogether = "";

            if (!string.IsNullOrWhiteSpace(focussed))
            {
                altogether = focussed;
            }
            if (!string.IsNullOrWhiteSpace(fundamentals))
            {
                if (!string.IsNullOrWhiteSpace(altogether))
                {
                    altogether += "," + fundamentals;
                } else
                {
                    altogether = fundamentals;
                }
            }
            if (!string.IsNullOrWhiteSpace(macros))
            {
                if (!string.IsNullOrWhiteSpace(altogether))
                {
                    altogether += "," + macros;
                }
                else
                {
                    altogether = macros;
                }
            }

What a dog's dinner!
Was This Post Helpful? 0
  • +
  • -

#3 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 14358
  • View blog
  • Posts: 57,599
  • Joined: 12-June 08

Re: neat comma removal

Posted 03 September 2018 - 08:03 AM

Honestly - yup.. used the series of IF statements. I imagine there is a nifty linq way, but it's early. :)

            string a = "1", b = "2", c = "";
            string foo = "";

            if (a != string.Empty)
                foo += $"{a},";
            if (b != string.Empty)
                foo += $"{b},";
            if (c != string.Empty)
                foo += $"{c},";

            if (foo.Substring(foo.Length - 1) == ",")
                foo = foo.Substring(0, foo.Length - 1);

Was This Post Helpful? 1
  • +
  • -

#4 Martyr2   User is offline

  • Programming Theoretician
  • member icon

Reputation: 5284
  • View blog
  • Posts: 14,105
  • Joined: 18-April 07

Re: neat comma removal

Posted 03 September 2018 - 08:07 AM

Well, if you can put the strings into an array, you could do something like this...

string names1 = "bob,ted,fred";
string names2 = "mary,dave";
string names3 = "";

string[] strs = new string[] { names1, names2, names3 };
string result = string.Join(",", strs.Where(x => !string.IsNullOrEmpty(x)));



Here we simply are using a predicate to loop through the string and only taking those which are not empty. The result array is then joined with the comma. End result here will then be bod,ted,fred,mary,dave with no trailing commas or commas for empty strings.

Obviously we can compress this down further if you are looking for something more compact, but I left it this way to be more explanatory. :)
Was This Post Helpful? 2
  • +
  • -

#5 andrewsw   User is offline

  • Unprocessable Entity
  • member icon

Reputation: 6595
  • View blog
  • Posts: 26,836
  • Joined: 12-December 12

Re: neat comma removal

Posted 03 September 2018 - 08:12 AM

Thanks both ;)

@modi, for your line 11

if (foo.Substring(foo.Length - 1) == ",")
    foo = foo.Substring(0, foo.Length - 1);

I suppose

foo = foo.TrimEnd( new[] { ',' });

is possibly a little 'neater'.
Was This Post Helpful? 0
  • +
  • -

#6 andrewsw   User is offline

  • Unprocessable Entity
  • member icon

Reputation: 6595
  • View blog
  • Posts: 26,836
  • Joined: 12-December 12

Re: neat comma removal

Posted 03 September 2018 - 08:27 AM

I suppose, as a colleague suggested, splitting them first to remove empty entries is also a reasonable approach:

string names1 = "bob,ted";
string names2 = "";
string names3 = "mary";

string names = names1 + "," + names2 + "," + names3;

string[] splitted = names.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

string result = string.Join(",", splitted);

result.Dump();
// bob,ted,mary

Was This Post Helpful? 0
  • +
  • -

#7 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7236
  • View blog
  • Posts: 15,081
  • Joined: 16-October 07

Re: neat comma removal

Posted 03 September 2018 - 04:10 PM

Hmm... this should work:
var result = string.Join(",", new string[] { names1, names2, names3 }
    .Select(s => s.Split(',').Select(x => x.Trim()).Where(x => x.Length > 0))
    .Aggregate((xs,ys) => xs.Concat(ys)));



For a more generalized solution:
private static string SplitJoin(char separtor, params string[] items) => string.Join(",", items
    .Select(s => s.Split(',').Select(x => x.Trim()).Where(x => x.Length > 0))
    .Aggregate((xs, ys) => xs.Concat(ys)));
...
Debug.WriteLine(SplitJoin(',', names1, names2, names3));


Was This Post Helpful? 1
  • +
  • -

#8 Skydiver   User is online

  • Code herder
  • member icon

Reputation: 6406
  • View blog
  • Posts: 21,979
  • Joined: 05-May 12

Re: neat comma removal

Posted 03 September 2018 - 05:42 PM

Do you really need the Aggregate() which will end up creating many temporary intermediate strings?

static string SplitJoin(char sep, params string[] items) =>
    string.Join("" + sep, 
                items.SelectMany(s => s.Split(sep)
                                       .Select(x => x.Trim())
                                       .Where(x => x.Length > 0)));



On the other hand, that Trim() isn't really doing us any favors.
Was This Post Helpful? 3
  • +
  • -

#9 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7236
  • View blog
  • Posts: 15,081
  • Joined: 16-October 07

Re: neat comma removal

Posted 04 September 2018 - 04:39 AM

@Skydiver: Agreed, SelectMany is a cleaner choice. I guess I'm just always excited when I get to use a fold in C#.

I don't know for sure that Aggregate will have such an impact... However, let's just double down on that fold :P:
private static string SplitJoin(char separtor, params string[] items) => items
    .Select(s => s.Split(separtor).Where(x => !string.IsNullOrEmpty(x)))
    .Aggregate("", (s, xs) => xs.Aggregate(s, (acc, x) => (acc == "") ? x : (acc + separtor + x)));




Note, I've ditched the trim in favor of that nice string helper function. I'm not even sure you'd always want to do that. You might want empties. In which case, I'll go with yours:
private static string SplitJoin(char separtor, params string[] items) =>
    string.Join("" + separtor, items.SelectMany(s => s.Split(separtor)));


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1