asp.net C#常用的字符串操作函数

作者:袖梨 2022-06-25

在c#中有直接表示字符串的类型,即string类型,他是char字符的集合,就像是char类型的制度数组

.NET Framework支持对字符串进行强大的处理功能,如字符串的查找,替换,格式化,调整等

字符串可以拼接 可以用 + 连接2个字符串

遍历字符串

可以像数组一样遍历字符串

代码如下 复制代码
string theString = "hello,world";
char theFristChar = theStringp[0];

字符是只读的,不能对单个字符进行修改

代码如下 复制代码
string theString = "hello,world";
theString[0] = 's';//wrong

与数组类似,可以用Length获得字符串长度

可以用foreach对字符串进行遍历

代码如下 复制代码

string theString = "hi,world";
foreach(char s in theString)
{
Console.Write(s);
}

可以通过ToCharArray()形式来获得表示字符串的字符数组

代码如下 复制代码

string theString = "hello World";
char[] theChars = theString.ToCharArray();

Trim去2头的空格,TrimStart去开头的指定字符串,TrimEnd去结尾的指定字符串

代码如下 复制代码

string s = "aaasssddd";
string s1 = "asasasddd";
Console.WriteLine(s.TrimStart(new char[] {'a','s'})); //ddd.
Console.WriteLine(s1.TrimStart(new char[] {'a','s'})); //sasasddd.

PadLeft或PadRight 添加开头和结尾的指定的字符

代码如下 复制代码

string s = "12345";
Console.WriteLine(s.PadLeft(10,'v')); //vvvvv12345
string s = "12345";
Console.WriteLine(s.PadLeft(5,'v')); //12345
string s = "12345";
Console.WriteLine(s.PadLeft(3,'v')); //12345

split 将字符串按指定的字符分割成字符串片段,得到的是字符串数组

代码如下 复制代码

string str = "one two_three=four";
string[] arr = str.Split(new char[] {' ','_','='});
foreach (string s in arr) {
Console.WriteLine(s);
}

substring 可以获取指定位置到结束的字符串片段 第一个参数是起始位置 第2个是截取字符串的长度

代码如下 复制代码

string str="0123456789";
string newStr = str.Substring(3);
Console.WriteLine(newStr);
string newStr2 = str.Substring(3,1);
Console.WriteLine(newStr2);

repalce 替换字符串指定的字符串

代码如下 复制代码

string str = "asdasdzxc";
Console.WriteLine(str.Replace('a', '1'));

remove 删除字符串中指定位置的字符串片段 第一参数是位置 第2个参数是长度

代码如下 复制代码
string str = "0123456789";
Console.WriteLine(str.Remove(5));
Console.WriteLine(str.Remove(5,1));

indexOf 查找指定的字符串在字符串中得位置,第一个参数是要查找的字符串 第2个参数起始位置

代码如下 复制代码

string str = "ok is ok";
Console.WriteLine(str.IndexOf("ok"));
Console.WriteLine(str.IndexOf("ok",1));

相关文章

精彩推荐