【问题标题】:How do I know which delimiter was used when delimiting a string on multiple delimiters? (C#)在多个分隔符上分隔字符串时,我如何知道使用了哪个分隔符? (C#)
【发布时间】:2013-07-15 21:25:59
【问题描述】:

我从文件中读取字符串,它们有多种样式:

item0 item1 item2 
item0,item1,item2
item0_item1_item2

我这样拆分它们:

string[] split_line = line[i].split(new char[] {' ',',','_'});

我更改了一个项目(列),然后我使用字符串生成器将字符串缝合在一起。 但是现在当把字符串放回去时,我必须使用正确的分隔符。

是否可以知道拆分字符串时使用了哪个分隔符?

更新 调用者会将第一个项目传递给我,以便我只更改该行。

【问题讨论】:

  • 这真的很烦人。不是要弄清楚如何做它,而是要弄清楚如何存储它。如果它们出现在单独的行中,您可以使用 char 分隔符字段创建一个 FileLine 类。

标签: c# string split delimiter


【解决方案1】:

除非您跟踪拆分操作(一次一个),否则您不会。 否则,您可以创建一个正则表达式来捕获项目和分隔符并从那里开始。

【讨论】:

  • you could create a regular expression, to catch the item and the delimiter and go from there. 我认为问题是如何?
  • @Saamorim,如果我知道 delim 是什么,那就很容易了!
  • 如何找到一些未出现在字符串中的字符(例如☃),将每个分隔符替换为以该字符开头的两个字符序列,然后根据它进行拆分?不一定是最高效的方法,但它应该有效。
  • @infinitloop,是的,你知道它们是什么!您已经提到它们:{' ',',','_'} 只是不要批量处理它们。一个可能的正则表达式可能是:(?<itemvalue>[^ ,_]+)(?<separator>[ ,_]?)
【解决方案2】:

您可以使用正则表达式来拆分字符串,而不是传入字符数组。这样做的好处是,您可以捕获分裂字符。 Regex.Split 将在数组中的元素之间插入任何捕获,如下所示:

string[] space = Regex.Split("123 456 789", @"([,_ ])");
// Results in { "123", " ", "456", " ", "789" }
string[] comma = Regex.Split("123,456,789", @"([,_ ])");
// Results in { "123", ",", "456", ",", "789" }
string[] underscore = Regex.Split("123_456_789", @"([,_ ])");
// Results in { "123", "_", "456", "_", "789" }

然后你可以编辑数组中的所有项目,比如

for (int x = 0; x < space.Length; x += 2)
    space[x] = space[x] + "x";
Console.WriteLine(String.Join("", space));
// Will print: 123x 456x 789x

在处理多个分隔符时要注意的一点是,是否有任何行中包含空格、逗号和下划线。例如

 37,hello world,238_3

此代码将保留所有不同的分隔符,但您的结果可能不是预期的。例如上面的输出将是:

 37x,hellox worldx,238x_3x

【讨论】:

    【解决方案3】:

    正如我提到的,调用者将第一个项目传递给我,所以我尝试了这样的事情:

    // find the right row
    if (lines[i].ToLower().StartsWith(rowID))
    {
      // we have to know which delim was used to split the string since this will be 
      // used when stitching back the string together.
      for (int delim = 0; delim < delims.Length; delim++)
      {
       // we split the line into an array and then use the array index as our column index
       split_line = lines[i].Trim().Split(delims[delim]);
       // we found the right delim
       if (split_line.Length > 1)
       {
         delim_used = delims[delim];
         break;
       }
      }
    }
    

    基本上我在分隔符上迭代每一行并检查生成的数组长度。如果大于 1,则表示 delim 有效,否则跳到下一个。我正在使用拆分函数属性“If this instance does not contain any of the characters in separator, the returned array consists of a single element that contains this instance.”

    【讨论】:

      猜你喜欢
      • 2015-01-10
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 2019-08-21
      • 1970-01-01
      • 2011-12-06
      相关资源
      最近更新 更多