C#急速入门-从helloworld开始(字符串)-1

145 阅读2分钟

写在前面的废话(可只看粗体)

本系列完全是自己c#的学习小抄,有可能会劝退读者。没有经验的需谨慎。 对我来说学习一个语言,让你感觉比别人牛x的地方,首先是你的pronounced(pro nang si de),像我这种处在金字塔底端的拖油瓶,能说个英语单词就感觉很牛x了,所以我每学一个技术,一个语言,独对名字很重要。

》》》》》》》》》》C# (pronounced "See Sharp") 所以跟我读C sha pu

对了,我这个笔记完全是跟着微软的文档学习的tour-of-csharp,提取我觉得要知道的东西,用来以后翻阅。我之前的学习方式都是copy代码,加简单注释,

变量声明

一般学习一个语言都是从如何定义一个变量,如何打印输出开始的,至少我学C的经验是这样的。当然有些语言不用声明变量类型。

string aFriend = "Bill"; 
Console.WriteLine(aFriend);

字符串内插(string interpolation) inter po lei shen

以前我学的都叫,格式化字符串,模板字符串啥的,感觉这个名字听起来就很舒爽,果真时代在进步。那位网友如果知道为什么叫这个,还请赐教。

上面学习了如何打印一个字符串,很多时候我们需要做字符串拼接,比如打印小票金额的时候,前面写上金额: 123元,这种时候,当然可以用+号拼接,

// 虽然例子不一样,但是你懂我的意思。
string aFriend = "Bill"; 
Console.WriteLine("Hello " + aFriend);

当然也可以用我们的内插语法,比如有好几个变量的时候,可以省去一堆加号,和双引号,而且看起来更加直观。一眼就能看出拼出来的字符串是什么样子。下面的例子顺便获取了字符串的长度。

// 虽然例子不一样,但是你懂我的意思。
string firstFriend = "Maria";
string secondFriend = "Sage"; 
Console.WriteLine($"My friends are {firstFriend} and {secondFriend}"); 
Console.WriteLine($"The name {firstFriend} has {firstFriend.Length} letters."); 
Console.WriteLine($"The name {secondFriend} has {secondFriend.Length} letters.");

字符串简单操作

我学习数据结构的时候,老师一直强调增删改查,其实写代码就是这些东西。c#对字符串的操作是不改变元字符串,每个操作都会新建一个字符串对象。

trim

花式去空白字符,去前,去后,去两边

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}]");

Replace

字符串替换

string sayHello = "Hello World!"; 
Console.WriteLine(sayHello); 
sayHello = sayHello.Replace("Hello", "Greetings");
Console.WriteLine(sayHello);

ToUpper/ToLower

大小写转换

string sayHello = "Hello World!"; 
Console.WriteLine(sayHello); 
sayHello = sayHello.Replace("Hello", "Greetings"); 
Console.WriteLine(sayHello);

Contains

查找字符串,返回是否包含某个字符串 结果为bool值

string songLyrics = "You say goodbye, and I say hello"; 
Console.WriteLine(songLyrics.Contains("goodbye")); 
Console.WriteLine(songLyrics.Contains("greetings"));