2

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

item0 item1 item2 
item0,item1,item2
item0_item1_item2

我这样拆分它们:

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

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

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

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

4

3 回答 3

3

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

于 2013-07-15T21:29:19.920 回答
1

您可以使用正则表达式来拆分字符串,而不是传入字符数组。这样做的好处是,您可以捕获分裂字符。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
于 2013-07-15T22:58:18.510 回答
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;
   }
  }
}

基本上我在分隔符上迭代每一行并检查生成的数组长度。如果大于 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.

于 2013-07-15T22:29:39.840 回答