【问题标题】:Split one string and put it in two arrays拆分一个字符串并将其放入两个数组中
【发布时间】:2020-08-26 03:36:34
【问题描述】:

我想将一个文本文件的多个字符串分别拆分为两个字符串(例如:car;driver)。我不知道如何将第一个单词放在array1 中,将第二个单词放在array2 中。因此,我尝试使用分号的 if 查询将 word1 的每个字母放入 array1 中,并与第二个单词相同,以便稍后将它们重新组合到单词中。

但我认为我所做的事情太复杂了,我现在卡住了,哈哈。

这里展示我的一段代码:

private void BtnShow_Click(object sender, EventArgs e)
        {
            LibPasswords.Items.Clear();

            string path = "passwords.txt";

            int counter = 0;

            using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            using (StreamReader reader = new StreamReader(fs))
            {
                while (reader.ReadLine() != null)
                {
                    counter++;

                }

                //for (int i = 0; i < counter; i++)
                //{
                //    var Website = reader.ReadLine().Split(';').Select(x => new String[] { x });
                //    var Passwort = reader.ReadLine().Split(';').Select(y => new String[] { y });
                //    LibPasswords.Items.Add(String.Format(table, Website, Passwort));
                //}

                string[] firstWord = new string[counter];
                string[] lastWord = new string[counter];

                int i = 0;
                int index = 0;
                while (reader.Peek() >= 0)
                {
                    string ch = reader.Read().ToString();
                    if (ch != ";")
                    {
                        firstWord[i] = ch;
                        i++;
                    }
                    else
                    {
                        index = 1;
                    }
                    while (reader.Peek() >= 0)
                    {
??????????????????????????????????
                    }
                }


            }
        }

对不起,我的英语不是我的母语。

【问题讨论】:

    标签: c# arrays string split


    【解决方案1】:

    由于您事先不知道有多少行,因此使用List&lt;string&gt; 而不是string[] 更方便。 List 会根据需要自动增加容量。

    你可以使用string.Split方法在';'处分割字符串成一个数组。如果结果数组的部分数量正确,您可以将这些部分添加到列表中。

    List<string> firstWord = new List<string>();
    List<string> lastWord = new List<string>();
    
    string fileName = @"C:\temp\SO61715409.txt";
    foreach (string line in File.ReadLines(fileName))
    {
        string[] parts = line.Split(new char[] { ';' });
        if (parts.Length == 2)
        {
            firstWord.Add(parts[0]);
            lastWord.Add(parts[1]);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-06
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多