Split string and remove spaces without .select

2019-02-20 12:05发布

(Limitations: System; ONLY)

I want to be able to split a string into an array and remove the spaces, I have this currently:

string[] split = converText.Split(',').Select(p => p.Trim()).ToArray();

EDIT: Also .ToArray cant be used apparently.

But the problem is, I can't use anything other then core system methods. So how can i trim spaces from a split or array without using .select or other non core ways.

Thanks!

2条回答
对你真心纯属浪费
2楼-- · 2019-02-20 12:22
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();
 }
查看更多
Viruses.
3楼-- · 2019-02-20 12:32

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();
查看更多
登录 后发表回答