【问题标题】:Split string and remove spaces without .select拆分字符串并删除没有 .select 的空格
【发布时间】:2013-04-16 04:14:42
【问题描述】:

(限制:系统;仅限)

我希望能够将一个字符串拆分为一个数组并删除空格,我目前有这个:

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

编辑:也 .ToArray 显然不能使用。

但问题是,我不能使用除核心系统方法之外的任何其他方法。那么如何在不使用 .select 或其他非核心方式的情况下从拆分或数组中修剪空格。

谢谢!

【问题讨论】:

    标签: c# arrays split core trim


    【解决方案1】:
    string[] split = 
      convertText.Split(new[]{',',' '}, StringSplitOptions.RemoveEmptyEntries);
    

    通过在您的拆分条件中添加一个空格,当您拥有 RemoveEmptyEntries 时,它将删除它们。但是,如果条目中有空格,这将失败。在这种情况下,您可以:-

    string[] split = 
          convertText.Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries);
    
     for (int index = 0; index < split.Count; index++)
     {
         split[index] = split[index].Trim();
     }
    

    【讨论】:

    • 这有点基于我知道你之前所做的......如果你有一个字符串“mega ounces, blah”,这将失败,因为它会在 mega 和 oucnes 之间分裂
    • 有机会在结果数组中得到一个空字符串。正如@Keith 所说,“如果条目中有空格,这将失败”
    【解决方案2】:

    它应该适用于所有情况:

    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();
        }
    }
    

    用法:

    string[] split = "text, ".SplitAndTrim(',').ToArray();
    

    【讨论】:

      猜你喜欢
      • 2014-02-11
      • 2021-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      相关资源
      最近更新 更多