c# 预定义的类型 string 表示 .Net类 System.String。关于字符串,需要知道的最重要的事情是:
- 字符串是Unicode字符的数组。
- string 中的字符串是不能被修改的
注意: 上面的操作不会改变 string, 而是返回一个新的副本(该副本也是不能被修改的)。
namespace HelloWorld_Console
{
class Program
{
static void Main(string []args)
{
string s = "Hi there.";
Console.WriteLine("{0}", s.ToUpper()); // Print uppercase copy
Console.WriteLine("{0}", s); // String is unchanged
}
}
}
使用 split 方法
该方法将一个字符串分割为若干个字符串, 然后并将它们以数组的形式返回。
static void Main(string[] args)
{
string s1 = "hi there! this, is: a string.";
char[] delimiters = { ' ', '!', ',', ':', '.' };
string[] words = s1.Split(delimiters);
foreach (string s in words)
Console.WriteLine("{0}", s);
}
该方法有很多重载的方法, 这里演示的是最简单的。
上面的程序是以 delimiters 中的字符 为参照标准, 然后以此标准分隔 s1 中的字符。
String.Concat (是一个静态方法):
连接 String 的一个或多个对象,或 String 的一个或多个对象值的 Object 表示形式。
static void Main(string []args) { string s = "huang"; string ss = "cheng"; string tt1 = String.Concat(ss,s); WriteLine(tt1); string tt2 = String.Concat("huang", "cheng", "tao"); WriteLine(tt2); string[] sss = { "hello ", "and ", "welcome ", "to ","this ", "demo! " }; Console.WriteLine(string.Concat(sss)); WriteLine(); WriteLine(s + ss); WriteLine(s+"huangchengtao"); }
String.CompareTo Method:
public int CompareTo (string strB);
- 返回一个整数,该整数指示 该对象是比 strB 大、还是小、还是相等。
- 注意: 如果两个 string 对象 在某些对应的位置上不一致, 则 string 对象比较的结果其实是 string 对象中第一对相异 字符比较的结果。 而且比较是大小写敏感的, 同个字符小写形式要比大写形式的大。
值 条件 小于零 此对象 是 小于 strB 零 此对象 与 strB 相等 大于零 此对象 是 大于 strB string s1 = "huang"; string s2 = "iuang"; var tt = s1.CompareTo(s2); /* 现在是 s1 跟 s2 比较,返回三个数 如果s1 和 s2 每个位置的字符相同并且大小也相同,返回0 如果 s1 中的某个字符 比 s2 对应的某个字符大,返回1 如果 s1 中的某个字符 比 s2 对应的某个字符小,返回 -1 */ WriteLine(tt); // 注意 “s1 跟 s2 比较 ” 和 “s2 跟 s1 比较” 返回的比较结果可能不一致 // 比如上面的 代码返回的是 -1 , 如果调换位置, 返回的是1
首先是 s1 中的字符h 跟 s2 中的 i 进行比较, 由于 i 在字典中比 h 大。 所以 s1 小于 s2. 则返回 -1。
返回1 表示 s1 确实 比s2大, 就相当于布尔值 true