char 与 string 互转 byte与string互转 list<string>与string[]互转 char与byte互转
class Program
{
static void Main(string[] args)
{
//string类型到数组 char[]数组
string str1 = "123";
string str2 = "abc";
string str3 = "表示表示";
char[] ch1= str1.ToCharArray();
char[] ch2 = str2.ToCharArray();
char[] ch3 = str3.ToCharArray();
//char[]数组到string类型
foreach(var x in ch3)
Console.WriteLine(x);//表 示 表 示
char[]ca1=new char[]{'1','表','中'};
string cs = new string(ca1);
Console.WriteLine(cs);//1表中
//string类型到数组 byte[]数组
byte[] by1 = Encoding.UTF8.GetBytes(str1);
byte[] by2 = Encoding.UTF8.GetBytes(str2);
byte[] by3 = Encoding.UTF8.GetBytes(str3);
foreach(var xx in by3)
Console.Write(xx + " ");//232 161 168 231 164 186 232 161 168 231 164 186 utf-8中字符占3字节
// byte[]数组到string类型
byte[] ba1 = new byte[] { 11,22,33};
// string bs = new string(ba1);//编译报错 无byte数组构造函数
string bs = Encoding.Default.GetString(ba1);//系统默认编码
Console.WriteLine(bs);//输出 ..! byte->ascll码的char->string
//char和byte char占两字节 可存汉字 byte为一字节 在C#中大小为[1,255]之中 否则编译报错
char c1='表';
// byte b1 = "1";//编译出错
// byte b2 = -1;//编译出错
byte b3 = 0;
byte b4 = 255;
// byte b5 = 256;//编译出错
Console.WriteLine("\n"+b4);//255
Console.WriteLine("\n" + c1);//表
//char 和 byte转换时 char->byte会转成数字 byte->char会转成ascll字符 下面的结果是在 日文系统下的输出结果 怎么算的未知 先搁着
char c2 = (char)b4;
Console.WriteLine(c2);//c2=255输出 y
byte b6 = (byte)c1;
Console.WriteLine(b6);//104
//string 数组到list<string>
string[]sa1=new string[]{"aaa","bbb","333"};
List<string> ls1 = new List<string>(sa1);
Console.WriteLine(ls1.Count);//结果为 3
//list<string>到 数组string
List<string> ls2 = new List<string>();
ls2.AddRange(new string[]{"123","234","345"});
string[] sa2 = ls2.ToArray();
Console.WriteLine(sa2.Length);//结果为 3
Console.Read();
}
}
补充: string str = "1234";
char[]cs= str.ToArray();//将str看成一个char的集合 类似List<string>ls=new List<string>{new string{"123","abc","vvv"}}; ls.toArray()
foreach (var item in cs)
{
Console.Write(item);//1,2,3,4,
}
string cv = "11223344567";
string[] nstr= cv.Split(str.ToArray());
Console.WriteLine("new array length:" + nstr.Length);//9 【1】【2】【3】【4】【1】【2】【3】【4】【567】
foreach (var items in nstr)
{
Console.Write(items);//输出567
}
Console.Read();