簡體   English   中英

String.Split結果出現問題

[英]Issue with String.Split result

我試圖從文本文件加載4行:

email:pass
email1:pass1
email2:pass2
email3:pass3

我使用了string.split,但是當我嘗試將其添加到我的列表時,它加載得不好。

這是我嘗試的:

List<string> AccountList = new List<string>();
Console.Write("File Location: ");
string FileLocation = Console.ReadLine();
string[] temp = File.ReadAllLines(FileLocation);
string[] tempNew = new string[1000];

int count = 0;
foreach(var s in temp)
{
    AccountList.Add(s.Split(':').ToString());
    count++;
}

我檢查了字符串在列表中的外觀,它們是這樣的:

System.String[]

我希望它是這樣的:

AccountList[0] = email
AccountList[1] = pass
AccountList[2] = email1
AccountList[3] = pass1

String.Split產生一個字符串數組

foreach(var s in temp)
{
    string[] parts = s.Split(':');
    string email = parts[0];
    string pass = parts[1];
    ...
}

要存儲這兩條信息,請創建一個帳戶

public class Account
{
    public string EMail { get; set; }
    public string Password { get; set; }
}

然后將您的帳戶列表聲明為List<Account>

var accountList = new List<Account>();
foreach(var s in File.ReadLines(FileLocation))
{
    string[] parts = s.Split(':');
    var account = new Account { EMail = parts[0], Password = parts[1] };
    accountList.Add(account);
}

請注意,您不需要temp變量。 File.ReadLines在循環進行時讀取文件,因此不需要將整個文件存儲在內存中。 請參閱: File.ReadLines方法 (Microsoft Docs)。

無需計數。 你可以用

int count = accountList.Count;

該列表比與電子郵件和密碼交錯的列表更易於處理。

您可以按索引訪問帳戶

string email = accountList[i].EMail;
string pass = accountList[i].Password;

要么

Account account = accountList[i];
Console.WriteLine($"Account = {account.EMail}, Pwd = {account.Password}");

從您的預期結果中可以嘗試一下, string.Split將返回一個字符串數組string[] ,盡管您的預期字符。

然后使用索引獲取字符串部分。

foreach(var s in temp)
{ 
   var arr = s.Split(':');
   AccountList.Add(arr[0]);
   AccountList.Add(arr[1]);
}

問題在於, Split返回一個字符串數組,該數組由在拆分字符之間找到的字符串部分組成,您將其視為字符串。

相反,可以通過獲取File.ReadAllLines (字符串數組)的結果並使用.SelectMany來從拆分:字符的每一行中選擇結果數組,從而簡化代碼(因此,您要為數組),然后在結果上調用ToList (因為您將其存儲在列表中)。

例如:

Console.Write("Enter file location: ");
string fileLocation = Console.ReadLine();

// Ensure the file exists
while (!File.Exists(fileLocation))
{
    Console.Write("File not found, please try again: ");
    fileLocation = Console.ReadLine();
}

// Read all the lines, split on the ':' character, into a list
List<string> accountList = File.ReadAllLines(fileLocation)
    .SelectMany(line => line.Split(':'))
    .ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM