C#学习 字符串操作 (3)

小溪(潺潺流水,润泽千里) / 2024-11-05 / 原文

字符串内插

Console.Write("字符串内插打印:");
Console.WriteLine($"Hello,{aFriend}");

Hello, World!

大括号内的多个变量

String bFriend="zhao";
Console.Write("大括号内多个变量:");
Console.WriteLine($"Hello,{aFriend} and {bFriend}");

定义变量后打印:Bill
字符串内插打印:Hello,Bill

大括号内支持属性和方法

Console.Write("大括号内访问属性:");
Console.WriteLine($"Hello,{aFriend} and {bFriend}'s Length is {bFriend.Length}!");
Console.Write("大括号内访问方法:");
Console.WriteLine($"Hello,{aFriend} and {bFriend}'s Length is {bFriend.ToUpper()}!");

大括号内多个变量:Hello,Bill and zhao
大括号内访问属性:Hello,Bill and zhao's Length is 4!
大括号内访问方法:Hello,Bill and zhao's Length is ZHAO!

空格处理

string temp1 = "     ni,hao!     ";
Console.WriteLine($"开头空格处理: {temp1.TrimStart()}");
Console.WriteLine($"尾部空格处理: {temp1.TrimEnd()}");
Console.WriteLine($"两端空格处理:{temp1.Trim()}");

开头空格处理: ni,hao!
尾部空格处理: ni,hao!
两端空格处理:ni,hao!

替换

string temp2 = "****ni,hao!";
Console.WriteLine($"替换所有*: {temp2.Replace("****","zhan san,")}");

替换所有*: zhan san,ni,hao!

搜索

string temp3="You are very good!";
Console.WriteLine($"搜索 very: {temp3.Contains("very")}");
Console.WriteLine($"是否以You开头: {temp3.StartsWith("You")}");
Console.WriteLine($"是否以good结尾: {temp3.EndsWith("good")}");

搜索 very: True
是否以You开头: True
是否以good结尾: False