如何从 txt 文件中剪切多个字符串#

How to cut multiple strings from txt filec#

我尝试了很多可能的解决方案来解决这个问题,但似乎从来没有奏效。我的问题如下:我有一个包含多行的 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

...

string[] y;

也一样

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

如果有人告诉我如何为我遇到的这个问题制作循环,我将不胜感激。

如果我正确理解你的问题,xxxxx 和 yyyyyy 会重复出现,以防出现类似的情况 11111 222222 11111 222222 11111 222222 它们之间有一个' 'space,所以

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

你可以为此使用 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>();

基本上,此代码将字符串拆分为 space,然后将偶数字符串放入一个数组,将奇数字符串放入另一个数组。

编辑

你在评论中说你不明白这一点:Where((c, i) => i % 2 == 0). 它所做的是获取每个字符串 (i) 的位置并用 2 对其进行 mod。这意味着,它将位置除以 2,并检查余数是否等于 0。这是获取数字是奇数还是偶数的方法。

编辑2

我的第一个答案只适用于一行。对于几个(因为你的输入源是一个包含多行的文件),你需要做一个 foreach 循环。或者您可以执行类似下一个示例代码的操作:读取所有行,将它们连接成一个字符串,然后 运行 结果上显示的代码:

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>();

如果我没理解错的话,你有多行,每行有两个字符串。然后,这是一个使用普通旧的答案:

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