系列文章——关于C#,你应该知道的2000件事情(002)

发布时间:2020-08-07 23:44:20 作者:ghcomeon
来源:网络 阅读:415

该系列文章从关于C#,你应该知道的2000件事情翻译

6. 用Reverse方法反转一个字符串

string funnyMan = "Roscoe Arbuckle";
string backwardsGuy = new string(funnyMan.Reverse().ToArray());
//backwardsGuy="elkcubrA eocsoR";

7. 使用String.Split把字符串分割成子字符串

string names = "John,Mary,Elvis,Ringo";//names = "John,Mary,Elvis,Ringo?I'm fine";
//Split参数是数组,所以可以多个字符作为分隔符
string[] nameList = names.Split(new char[] { ','});//new char[] { ',','?','\'',' '}
Console.WriteLine(nameList[0]);    // John
Console.WriteLine(nameList[1]);    // Mary
Console.WriteLine(nameList[2]);    // Elvis
Console.WriteLine(nameList[3]);    // Ringo

也可以使用循环来遍历string数组
string names = "John - Mary - Elvis - Ringo";
// Same result as before - we get four names, without spaces or dash
string[] nameList = names.Split(new string[] { " - " }, 
                                      StringSplitOptions.RemoveEmptyEntries);
foreach (string str in nameList)
{
    Console.WriteLine(str);
}
参数指定移除空格

8.字符串函数连在一起操作

char[] braces = new char[] { '{', '}' };
string s = "{This|That|Such}";
s = s.Replace("|", " and ").Trim(braces).Insert(0, "=> ").ToLower();
Console.WriteLine(s);       // => this and that and such

可以将操作的字符串的函数在一行中实现

9. 通过Trim方法在字符串中减少前导和尾随字符

string s = "  The core phrase";  // 2 leading spaces, 1 trailing
s = s.Trim();     // s = "The core phrase"
注意:(1)Trim()方法默认只是去掉开头和结尾的空格,不会去掉字符串中间的空格。
    (2)任何对字符串的操作,都不改变原字符串的值,都会返回一个新的实例,需要赋值给一个变量,才能得到对字符串操作结果的字符串。
string s = "  {The core phrase,} ";
s = s.Trim(new char[] { ' ', '{', ',', '}' });// s = "The core phrase"
s = " {Doesn't {trim} internal stuff }";
s = s.Trim(new char[] { ' ', '{', '}' });// s = "Doesn't {trim} internal stuff"

string s = "{Name}";
char[] braces = new char[] { '{', '}' };
string s2 = s.TrimStart(braces); // s2 = "Name}"
string s3 = s.TrimEnd(braces); // s3 = "{Name"

10. 插入和移除子字符串

可以通过String.Insert方法在一个字符串的任何位置插入一个子字符串。

string s = "John Adams";
int n = s.IndexOf("Adams");
s = s.Insert(n, "Quincy "); // s now "John Quincy Adams"

注意:字符串时不可变的,即使调用Insert方法,如果未把操作的结果赋给任何变量,对原字符串没有任何影响。

string s = "John Adams";
s.Insert(5, "Quincy "); // Allowed, but s is not changed

可以通过String.Remove方法指定下标开始,指定长度的子字符串,字符串的下标从0开始。

string s = "OHOLEne";
s = s.Remove(1, 4); // Start at position 1, remove 4 characters,Now s is "One"


推荐阅读:
  1. MySQL应该如何备份与恢复
  2. wordpress 不同分类下的文章使用不同模版

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

200

上一篇:Python基础教程:一次性搞定 Django Form

下一篇:立体运维架构与定位

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》