c# String ,String[] 和 List<String>之间的转换

 C#对字符串进行处理时,经常需要进行String,String[]和List<String>之间的转换

本文分析一下它们的差异和转换

一.

  1. String > String[]

String s = "ab cd ef gh";
String[] sArray = s.Split(' ');

  2. String[] > String

string[] sArray = {"ab", "cd", "ef", "gh"};
string s = String.Join(" ", sArray);
//s = "ab cd ef gh";

  3.String[] > List<String>

string[] sArray = { "ab", "cd", "ef", "gh" };
List<String> list = new List<string>(sArray);

  4.List<String> > String[]

List<String> list = new List<string>();
list.Add("ab");            
list.Add("cd");            
list.Add("ef");            
list.Add("gh");        
string[] sArray = list.ToArray();

  5.String和List<String>之间的转换可以使用String[]来中转完成

二.

  1. String类型有很多常用的字符串操作成员

    

    字符串是不可变的,虽然这些方法看起来都会改变字符串对象,其实,它们不会改变而是返回了新的

    副本。对于一个String,任何“改变”都会分配一个新的恒定字符串。 

String s = "ab cd ef gh";
Console.WriteLine("{0}", s.ToUpper());
Console.WriteLine("{0}", s);
/*
返回结果:
AB CD EF GH
ab cd ef gh
*/

    2. String[]是定长的,String[]一般是在确定字符串数组的长度的情况下使用 

    3. List< String >一般在数组的长度会发生变化的情况下使用,例如在数组中间插入一个字符串

原文地址:https://www.cnblogs.com/vijing/p/10518851.html