字符串(string)
C# 字符串(String)
在 C# 中,您可以使用字符数组来表示字符串,但是,更常见的做法是使用 string 关键字来声明一个字符串变量。
string 关键字是 System.String 类的别名。
创建 String 对象 您可以使用以下方法之一来创建 string 对象:
通过给 String 变量指定一个字符串
通过使用 String 类构造函数
通过使用字符串串联运算符( + )
通过检索属性或调用一个返回字符..
String 类有以下两个属性:
1. Chars 在当前 String 对象中获取 Char 对象的指定位置。
2. Length 在当前的 String 对象中获取字符数。
String 类有许多方法用于 string 对象的操作。下面的表格提供了一些最常用的方法:
实例1:
using System; namespace StringApplication { class Program { static void Main(string[] args) { //字符串,字符串连接 string fname, lname; fname = "Rowan"; lname = "Atkinson"; string fullname = fname + lname; Console.WriteLine("Full Name: {0}", fullname); //通过使用 string 构造函数 char[] letters = { ‘H‘, ‘e‘, ‘l‘, ‘l‘,‘o‘ }; string greetings = new string(letters); Console.WriteLine("Greetings: {0}", greetings); //方法返回字符串 string[] sarray = { "Hello", "From", "Tutorials", "Point" }; string message = String.Join(" ", sarray); Console.WriteLine("Message: {0}", message); //用于转化值的格式化方法 DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1); string chat = String.Format("Message sent at {0:t} on {0:D}", waiting); Console.WriteLine("Message: {0}", chat); Console.ReadKey() ; } } } //当上面的代码被编译和执行时,它会产生下列结果: //Full Name: Rowan Atkinson //Greetings: Hello //Message: Hello From Tutorials Point //Message: Message sent at 5:58 PM on Wednesday, October 10, 2012下面的实例演示了上面提到的一些方法:
比较字符串
using System; namespace StringApplication { class StringProg { static void Main(string[] args) { string str1 = "This is test"; string str2 = "This is text"; if (String.Compare(str1, str2) == 0) { Console.WriteLine(str1 + " and " + str2 + " are equal."); } else { Console.WriteLine(str1 + " and " + str2 + " are not equal."); } Console.ReadKey() ; } } } 当上面的代码被编译和执行时,,它会产生下列结果: This is test and This is text are not equal.温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/71415.html
- 上一篇:Linux系统与windows系统文件同步
- 下一篇:不安全代码(Unsafe)