tags:

views:

241

answers:

5

Hello,

I want to output a string that welcomes a used to the application. I have the user's first, middle and last name. I would like to write the user's full name, i.e. "Hello {0} {1} {2}" with first, middle and last being the parameters. However, If the middle name is empty, I don't want two spaces between the first and the last name, but rather only one space. I can obviously do it with an "if", but is there a more elegant way to achieve this?

Thanks

A: 

One way to achieve this would be to put the space into the parameter string. For example (only first and last name as an example)

Console.WriteLine("Hello {0}{1}{2}",
  firstName,
  String.IsNullOrEmpty(firstName) ? String.Empty : " ", 
  lastName);
JaredPar
where's the middle name?
maxwellb
+2  A: 
"Hello {0} {1}{3}{2}"

where

{3} = param1.IsNullOrEmpty() ? "" : " "
VVS
this still gives you 2 spaces?
Jimmy
@Jimmy: the spaces are conditional to the parameter at position {1}.. so no, you don't get 2 spaces if param1 is null or empty.
VVS
@VVS: if {1} is null or empty, then the result is {0}{2}. You should turn one of the {3}'s into a space, i think.
Jimmy
no you get 0 spaces and have "Hello FirstLast".
maxwellb
VVS
+2  A: 

It might be worthwhile to make a Name class that has a Full property that takes care of that logic (i.e. will print "John Smith" if there is no middle name or "John A. Smith" if there is).

Then your code would be:

var name = new Name(first, middle, last);
var message = string.Format("Hello {0}", name.Full);

You could also consider adding LastFirstMiddle property (to get a "Smith, John A." formatted string) and any other properties that would make sense with the Name class.

cdmckay
+3  A: 
string.Format("{0} {1} {2}", first, middle, last).Replace("  "," ")
Jimmy
I like that one the best. I could use "Hello "+your solution.
Roee Adler
A: 
var hello =
    (from name in new[] { "Hello", firstName, middleName, lastName }
     where !string.IsNullOrEmpty(name))
     .Aggregate((xs, x) => xs + " " + x);

or

var hello = string.Join(" ", 
    (from name in new[] { "Hello", firstName, middleName, lastName }
     where !string.IsNullOrEmpty(name))
     .ToArray());
Joe Chung
If you have a golden hammer, everything looks like a nail, right? :-)Seriously though, don't you agree that this syntax obfuscates the intention here, rather than keeping it readable?
jeroenh
I was thinking the same thing.
cdmckay