C#中的字符串

字符串初始化

//字符串是常量,可以直接赋值给string【比较常用】 string name = "Jack"; Console.WriteLine(name); //利用字符串数组初始化 //构造方法:public string(char[] value) char[] charArr = {'a','c','b','c' }; string a = new string(charArr); Console.WriteLine(a); //提取字符数组中一部分初始化 //构造方法:public string(char[]value,int offset,int count)char[] charArray = { '是','减','哈', '他', '哇', '台', '汉' }; string b = new string(charArray,4,2); Console.WriteLine(b); Console.ReadLine();

【C#中的字符串】空字符串与空引用的区别
string str1 = ""; string str2 = null; Console.WriteLine(str1.ToString()); //异常,System.NullReferenceException:“未将对象引用设置到对象的实例。” Console.WriteLine(str2.ToString()); Console.ReadLine();

获取字符串的长度
string pwd = "12345 6abcedds"; Console.WriteLine(pwd.Length); Console.ReadLine();

获取指定位置的字符
string pwd = "12345 6abcedds"; char ch = pwd[3]; Console.WriteLine(ch); Console.ReadLine();

获取子字符串的索引位置
static void Main() { //获取第一次出现的索引 string str = "We are the world"; int a = str.IndexOf("e"); Console.WriteLine(a); //从指定位置开始 int b = str.IndexOf("e",3); Console.WriteLine(b); //从指定位置开始起数个字符内获取第一次出现的索引 int c = str.IndexOf("e", 3,5); Console.WriteLine(c); int d = str.LastIndexOf('r'); Console.WriteLine(d); Console.ReadLine(); }

判断字符串首尾内容
static void Main() { string fileName = "Demo.CS"; bool flag = fileName.EndsWith(".CS",true,null); string str = "Keep on going never give up"; bool flag = str.StartsWith("Keep"); Console.WriteLine(flag); Console.ReadLine(); }

比较字符串
string str1 = "Jack"; string str2 = "jack"; //Compare Console.WriteLine(string.Compare(str1,str2,true)); //CompareTo Console.WriteLine(str1.CompareTo(str2)); //Equals方法 Console.WriteLine(str1.Equals(str2)); Console.WriteLine(string.Equals(str1,str2)); Console.ReadLine();

字符串大小写转换
string str = "Learn and live"; Console.WriteLine(str.ToLower()); Console.WriteLine(str.ToUpper()); Console.ReadLine();

去字符串空格
static void Main(string[] args) { string greeting = "Hello World"; Console.WriteLine($"[{greeting}]"); //去掉前空格 string trimmedGreeting = greeting.TrimStart(); Console.WriteLine($"[{trimmedGreeting}]"); //去掉后空格 trimmedGreeting = greeting.TrimEnd(); Console.WriteLine($"[{trimmedGreeting}]"); //去掉前后空格 trimmedGreeting = greeting.Trim(); Console.WriteLine($"{trimmedGreeting}"); Console.ReadLine(); }

替换Replace()
static void Main(string[] args) { string sayHello = "Hello World"; Console.WriteLine(sayHello); sayHello = sayHello.Replace("World","Jack"); Console.WriteLine(sayHello); Console.ReadLine(); }

搜索字符串Contains 方法返回布尔值
string str = "You say goodbye,and I say hello"; Console.WriteLine(str.Contains("goodbye")); Console.WriteLine(str.Contains("jack")); string songLyrics = "You say goodbye, and I say hello"; Console.WriteLine(songLyrics.StartsWith("You")); Console.WriteLine(songLyrics.StartsWith("goodbye")); Console.WriteLine(songLyrics.EndsWith("hello")); Console.WriteLine(songLyrics.EndsWith("goodbye")); Console.ReadLine();

    推荐阅读