在多个分隔符上分隔字符串时,如何知道使用了哪个分隔符? (C#)

时间:2013-07-15 21:26:00

标签: c# string split delimiter

我从文件中读取字符串,它们有各种风格:

item0 item1 item2 
item0,item1,item2
item0_item1_item2

我将它们拆分成这样:

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

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

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

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

3 个答案:

答案 0 :(得分:3)

除非你跟踪分裂行动(当时只有一个),否则你不会。 否则,您可以创建一个正则表达式,以捕获项目和分隔符并从那里开始。

答案 1 :(得分:0)

正如我所提到的那样,来电者将第一项传给了我,所以我尝试了这样的事情:

// 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;
   }
  }
}

基本上我迭代delims上的每一行并检查结果数组的长度。如果是> 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.

答案 2 :(得分:0)

您可以使用正则表达式来分割字符串,而不是传入一个字符数组。这样做的好处是可以捕获分裂字符。 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
相关问题