【问题标题】:Splitting string by space, clarification needed [duplicate]按空格分割字符串,需要澄清[重复]
【发布时间】:2019-12-02 07:39:37
【问题描述】:

我有一个正在尝试测试的方法

    public static string BySpace(string s, int position)
    {
        return s.Split()[position];
    }

我周围有一个测试功能

    [Theory]
    [InlineData("a  b   c   d")]
    [InlineData(" a  b   c   d")]
    [InlineData("a  b   c   d ")]
    [InlineData("a b c d")]
    [InlineData(" a b c d ")]
    public void TestParseToList(string s)
    {
        Assert.Equal("a", Util.BySpace(s, 0));
        Assert.Equal("b", Util.BySpace(s, 1));
        Assert.Equal("c", Util.BySpace(s, 2));
        Assert.Equal("d", Util.BySpace(s, 3));
    }

一堆内联数据测试失败。可以看出我在玩 Space & Tab。

想要的效果:取一个字符串,用任意空格分割

请问我错过了什么?如何获取一个字符串并按空格分割它

我尝试了以下所有方法都无济于事

// return s.Split()[position];
// return s.Split(' ')[position];
// return s.Split("\\s+")[position];  <----- i had high hopes for this one
// return s.Split(null)[position];
// return s.Split(new char[0])[position];
creturn s.Split(new char[0], StringSplitOptions.RemoveEmptyEntries)[position]);

【问题讨论】:

  • return System.Text.RegularExpressions.Regex.Split( s, @"\s+");
  • 谢谢@Aggragoth。为什么常规拆分不起作用?
  • 据我所知,您拥有的基于正则表达式的拆分,即。 s.Split("\\s+") 不是 C# 中的功能,但它在 java 中。如果您还试图排除任一侧的空格,我可能会修剪字符串的每一侧以获得空格
  • @Aggragoth 你抓住了我。恢复 Java 的家伙在这里自学 c# :)

标签: c# split


【解决方案1】:

当您调用 Split 时,您可以传递多个要拆分的字符:

return s.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries)[position];

在这种情况下,您有空格 ' ' 和制表符 '\t'

【讨论】:

  • 简单地感谢格德
【解决方案2】:

以下将解决您的问题:

//avoid null reference exception
if(!string.IsNullOrEmpty(s))
{
   //remove any whitespace to the left and right of the string
   s = s.Trim();
   // Here we use a regular expression, \s+
   // This means split on any occurrence of one or more consecutive whitespaces.
   // String.Split does not contain an overload that allows you to use regular expressions
   return System.Text.RegularExpressions.Regex.Split(s, "\\s+")[position];
}
else { return null; }

【讨论】:

  • 请致电null检查
猜你喜欢
  • 2017-11-10
  • 2013-10-11
  • 2023-03-12
  • 2017-03-09
  • 1970-01-01
  • 2011-12-28
  • 2012-07-05
  • 2011-08-18
  • 2016-12-26
相关资源
最近更新 更多