Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Friday, January 8, 2016

Writing the string.format over multiple lines

Writing the string.format over multiple lines


public override string ToString()  {      return String.Format("Name : {0} Date Of Birth : {1: dd/MM/yyyy} Gender : {2} Telephone : {3}", _name, _dob, _gender, _tel);  }  

How would I change this so that each Heading is written on a separate line so name is on line 1, DOB line 2, Gender line 3, etc?

Answer by Millie Smith for Writing the string.format over multiple lines


Using the \r and \n carriage return and linefeed characters.

public override string ToString()   {       return String.Format("Name : {0}\r\nDate Of Birth : {1: dd/MM/yyyy}\r\nGender : {2}\r\nTelephone : {3}", _name, _dob, _gender, _tel);   }  

Answer by Ed Plunkett for Writing the string.format over multiple lines


Multiline string literal. Prefix it with the "at" sign, @, and you can put actual newlines in the string itself. Much more readable than \r\n.

public override string ToString()   {       return String.Format(  @"Name : {0}  Date Of Birth : {1: dd/MM/yyyy}  Gender : {2}  Telephone : {3}",       _name, _dob, _gender, _tel);   }  

Answer by Andrew for Writing the string.format over multiple lines


Add the new line carriage \n:

public override string ToString()  {      return String.Format("Name : {0} \nDate Of Birth : {1: dd/MM/yyyy} \nGender : {2} \nTelephone : {3}", _name, _dob, _gender, _tel);  }  

Answer by dotctor for Writing the string.format over multiple lines


I recommend that you use Environment.NewLine because you can trust it in different runtimes

return String.Format("Name : {1}{0}Date Of Birth : {2: dd/MM/yyyy}{0}Gender : {3}{0}Telephone : {4}",      Environment.NewLine, _name, _dob, _gender, _tel);  

Answer by Enigmativity for Writing the string.format over multiple lines


I would go with this approach:

public override string ToString()  {      var nl = Environment.NewLine;      return          $"Name : {_name}{nl}"          + $"Date Of Birth : {_dob:dd/MM/yyyy}{nl}"          + $"Gender : {_gender}{nl}"          + $"Telephone : {_tel}";  }  

Or this, if you think it is clearer:

public override string ToString()  {      return          $"Name : {_name}{Environment.NewLine}"          + $"Date Of Birth : {_dob:dd/MM/yyyy}{Environment.NewLine}"          + $"Gender : {_gender}{Environment.NewLine}"          + $"Telephone : {_tel}";  }  


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.