创建 String 对象

您可以使用以下方法之一来创建 string 对象:

  • 通过给 String 变量指定一个字符串
  • 通过使用 String 类构造函数
  • 通过使用字符串串联运算符( + )
  • 通过检索属性或调用一个返回字符串的方法
  • 通过格式化方法来转换一个值或对象为它的字符串表示形式

下面的实例演示了这点:

实例

  1. using System;
  2. namespace StringApplication
  3. {
  4. class Program
  5. {
  6. static void Main(string[] args)
  7. {
  8. //字符串,字符串连接
  9. string fname, lname;
  10. fname = "Rowan";
  11. lname = "Atkinson";
  12. string fullname = fname + lname;
  13. Console.WriteLine("Full Name: {0}", fullname);
  14. //通过使用 string 构造函数
  15. char[] letters = { 'H', 'e', 'l', 'l','o' };
  16. string greetings = new string(letters);
  17. Console.WriteLine("Greetings: {0}", greetings);
  18. //方法返回字符串
  19. string[] sarray = { "Hello", "From", "Tutorials", "Point" };
  20. string message = String.Join(" ", sarray);
  21. Console.WriteLine("Message: {0}", message);
  22. //用于转化值的格式化方法
  23. DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
  24. string chat = String.Format("Message sent at {0:t} on {0:D}", //Format方法用于格式化时间
  25. waiting);
  26. Console.WriteLine("Message: {0}", chat);
  27. Console.ReadKey() ;
  28. }
  29. }
  30. }

当上面的代码被编译和执行时,它会产生下列结果:
Full Name: RowanAtkinson
Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 17:58 on Wednesday, 10 October 2012
语雀内容