【C#】字符串使用汇总

1、排序
char[] tmp = str.ToArray();
Array.Sort(tmp);                    //按ASCII排序

 

2、字节数组转换为ASCII字符串

           // 字节数组
            byte[] ba = new byte[] { 119,104,97,116,50,49,46,99,111,109 };
            // 转换为ASCII的字符
            string s = Encoding.ASCII.GetString(ba);
//转换ASCII字符串转换为字节数组 byte[] ba = Encoding.UTF8.GetBytes(s)

 

3、string与char[]之间的转换

string ss = "abcdefg";
char[] cc = ss.ToCharArray();
string s = new string(cc);

4、byte[]与char[]之间的转换

byte[] bb;
char[] cc = Encoding.ASCII.GetChars(bb);
byte[] bb = Encoding.ASCII.GetBytes(cc);

5、提取字符串中的数字

str = System.Text.RegularExpressions.Regex.Replace(str, @"[^0-9]+", "")

str = Regex.Replace(str, @"[^d.d]", "")//带小数点

链接

 

6、判断字符串数组中某字符是否存在

int exist = Array.IndexOf(tmpArray, str);
 //tmpArray为字符串数组,str为判断依据
if(exist == -1) //该字符不存在

{
     //代码
}

 

7、字符串去重

char[] chars = newstr.ToList<char>().Distinct().ToArray<char>();

 

8、字符串转置
string newstr = new string(str.ToArray().Reverse().ToArray());

 

/*******相与枕藉乎舟中,不知东方之既白*******/
原文地址:https://www.cnblogs.com/Mars-0603/p/15343645.html