2017-03-23 45 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]; 
     } 
    } 
相關問題