Split string and remove spaces without .select

北战南征 提交于 2019-12-01 13:12:38
string[] split = 
  convertText.Split(new[]{',',' '}, StringSplitOptions.RemoveEmptyEntries);

by adding a space to your split criteria, it will get rid of them when you have RemoveEmptyEntries. However this will fail if there are entries with spaces in them. In which case you could just :-

string[] split = 
      convertText.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries);

 for (int index = 0; index < split.Count; index++)
 {
     split[index] = split[index].Trim();
 }

It should work for all cases:

public static class TrimHelper
{
    public static string[] SplitAndTrim(this string str, char splitChar, StringSplitOptions options = StringSplitOptions.RemoveEmptyEntries)
    {
        List<string> result = new List<string>();

        if (str != null)
        {
            foreach (var item in str.Split(splitChar, options))
            {
                string val = item.Trim();

                if (options == StringSplitOptions.RemoveEmptyEntries && val == string.Empty)
                    continue;

                result.Add(val);
            }
        }

        return result.ToArray();
    }
}

Usage:

string[] split = "text, ".SplitAndTrim(',').ToArray();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!