2017-03-23 48 views
0

我尝试了很多可能的解决方案来解决这个问题,但它似乎没有工作。我的问题如下:我有一个包含多行的txt文件。每一行都有类似:如何从txt文件夹中剪切多个字符串#

xxxxx yyyyyy 
xxxxx yyyyyy 
xxxxx yyyyyy 
xxxxx yyyyyy 
... 

我想在字符串中xxxxx的一个阵列和另一个阵列的yyyyy存储,对txt文件的每一行,像

string[] x; 
string[] y; 

string[1] x = xxxxx; // the x from the first line of the txt 
string[2] x = xxxxx; // the x from the second line of the txt 
string[3] x = xxxxx; // the x from the third line of the txt 

.. 。

and string[] y;

...但我不知道如何...

我非常感激,如果有人告诉我如何使循环对于这个问题,我有。

+0

问题didnt格式化好的......在file.txt的,每一行都有XXXXX YYYYY文本。 – thecner

+0

那么你有两个(只有两个)类别的字符串,你想分成两个不同的数组?或者你需要检查类别数量(重复)? – pijemcolu

+0

只有2个类别,xxxxx和yyyyy – thecner

回答

3

你可以使用LINQ此:

string test = "xxxxx yyyyyy xxxxx yyyyyy xxxxx yyyyyy xxxxx yyyyyy"; 
string[] testarray = test.Split(' '); 
string[] arrayx= testarray.Where((c, i) => i % 2 == 0).ToArray<string>(); 
string[] arrayy = testarray.Where((c, i) => i % 2 != 0).ToArray<string>(); 

基本上,这种代码通过一个空间拆分字符串,然后放入一个阵列的偶数串和奇数那些在另一个。

编辑

您的评论说你不明白这一点:Where((c, i) => i % 2 == 0).它所做的是采取每个字符串(i)的位置和做它用2国防部这意味着,它将位置除以2并检查余数是否等于0.如果数字是奇数或偶数,就是得到这种方式。

EDIT2

我的第一个答案只适用于一行。对于几个(因为你的输入源是一个文件有几行),你需要做一个foreach循环。或者你也可以做类似的示范代码:读取所有行,在一个字符串加入他们的行列,然后运行prevously显示结果代码:

string[] file=File.ReadAllLines(@"yourfile.txt"); 
string allLines = string.Join(" ", file); //this joins all the lines into one 
//Alternate way of joining the lines 
//string allLines=file.Aggregate((i, j) => i + " " + j); 
string[] testarray = allLines.Split(' '); 
string[] arrayx= testarray.Where((c, i) => i % 2 == 0).ToArray<string>(); 
string[] arrayy = testarray.Where((c, i) => i % 2 != 0).ToArray<string>(); 
+0

这个工程甚至如果xxxxx和yyyyy是另一回事?即时通讯问,因为我的大脑有点冻结试图了解.Where((c,i)=> i%2 == 0)部分:p – thecner

+0

是的,只要它们分开由一个单一的空间 – p3tch

+0

这个解决方案不会在内容上传递,只有在我看到的位置 – Pikoh

0

如果我正确理解你的问题,为XXXXX和YYYYYY显示屡,而这情况下,类似的东西11111 222222 11111 222222 11111 222222 它们之间有一个'空间,所以

1. you may split the line one by one within a loop 
2. use ' ' as delimiter when split the line 
3. use a counter to differentiate whether the string is odd or even and store them separately within another loop 
+0

要小心,分隔符是一个字符,并应标记为'' – GaelSa

+0

是的,如果您使用C#,更新 – Aaron

0

如果我理解正确的话,您有多条线路,每行有两个字符串。于是,这里是使用普通的旧的答案:

public static void Main() 
    { 
     // This is just an example. In your case you would read the text from a file 
     const string text = @"x y 
xx yy 
xxx yyy"; 
     var lines = text.Split(new[]{'\n', '\r'}, StringSplitOptions.RemoveEmptyEntries); 
     var xs = new string[lines.Length]; 
     var ys = new string[lines.Length]; 

     for(int i = 0; i < lines.Length; i++) 
     { 
      var parts = lines[i].Split(' '); 
      xs[i] = parts[0]; 
      ys[i] = parts[1]; 
     } 
    } 
相关问题