我正在C#中建立一个新项目,并想用此字符分割字符串,但保持返回空白
public static List<string> Tokinization(string stringy)
{
List<string> terms=new List<string>();
char[] seps = new char[] { ' ',',','.','\n',};
foreach (string ss in stringy.Split(seps))
{
terms.Add(ss);
}
return terms;
}
输入是:
stringy="Mountain bike"
实际结果是:
terms{"","","",.........,"","Mountain","bike"}
但是,我希望输出terms{"Mountain","bike"}
答案 0 :(得分:2)
如果要分割整个换行符序列,而不仅仅是'\n'
,则可以使用重载,将字符串数组和选项作为参数。
public static List<string> Tokinization(string stringy)
{
List<string> terms = new List<string>();
foreach (string ss in stringy.Split(new string[] { " ", ",", ".", Environment.NewLine }, StringSplitOptions.None))
{
terms.Add(ss);
}
return terms;
}
如果您通常还希望省略空令牌,则也可以使用相应的选项。
public static List<string> Tokinization(string stringy)
{
List<string> terms = new List<string>();
foreach (string ss in stringy.Split(new string[] { " ", ",", ".", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
{
terms.Add(ss);
}
return terms;
}