如何比较文本文件中数组内的字符串

本文关键字:数组 字符串 文件 文本 何比较 比较 | 更新日期: 2023-09-27 18:36:10

我正在为一个读取文本文件的ATM项目编写代码。文本文件按以下格式写入:

账号 * 姓名 * 密码 * 支票余额 * 保存余额

因此,我将其传递到将它们拆分为数组的方法中。

public void linesplitter (string line)
    {
     string[] split = line.Split('*');
        account = int.Parse(info [0]) ; 
        name = info [1] ; 
        pin = int.Parse(info [2]) ; 
        check = info [3] ; 
        saving = info [4] ; 
}

因此,当用户输入帐号时,它会进入登录屏幕,他们将在其中输入与帐号关联的名称和 PIN。

我的问题是如何将姓名和密码与帐号进行比较?

如何比较文本文件中数组内的字符串

示例。

 List<AccountDetails> accountDetails = new List<AccountDetails>();
        //Declare class to store your info
        public class AccountDetails
        {
            public String account { get; set; }
            public String name { get; set; }
            public String pin { get; set; }
            public String check { get; set; }
            public String saving { get; set; }
        }
        //This function is a just an example, you need to expand it to fit your solution
        public void linesplitter(String line)
        {
            //You can place your text file reader code here. 
            //And call this function from Page_Load.
            AccountDetails dtl = new AccountDetails();
            string[] split = line.Split('*');
            dtl.account = int.Parse(info[0]);
            dtl.name = info[1];
            dtl.pin = int.Parse(info[2]);
            dtl.check = info[3];
            dtl.saving = info[4];
            //Every line from your text file will store to the Global List as declare in 1st line.
            accountDetails.Add(dtl);
        }

        //this is the function that trigger by your Button Event.
        //Pass in parameters to this function to get account details.
        //So the output for this function, something like 
        //if(result == null)
        //  login fail. etc
        public AccountDetails GetAccountDetails(String AccountNumber, String Name, String Pin)
        {
            var result = (from a in accountDetails
                          where a.account == AccountNumber
                          && a.name == Name
                          && a.pin == Pin
                          select a).FirstOrDefault();                                               
            return result;
        }

作为一种选择,您必须将所有信息从文本文件收集到包装类实例的集合中,然后在用户输入帐号后,您按编号在集合中找到一个项目,如果存在此类项目,则期望所需的引脚和名称,进行验证检查等...

例如,您创建类:

class AccountInfo
{
    public long AccountNumber { get;set; }
    public int Pin { get;set; }
    public string Name { get;set; }
    public string Check { get;set; }
    public string Saving { get;set; }
}

并将您的文本数据转换为项目集合:

var textLines = sourceTextData.Split(''r'n').ToList();
var accountsCollection = textLines.Select(i => 
new AccountInfo
{ 
  AccountNumber = Convert.ToDouble(i.Split('*')[0]),
  Pin = Int32.Parse(i.Split('*')[1]),
  Name = i.Split('*')[2],
  Check = i.Split('*')[3],
  Saving = i.Split('*')[4]
}).ToList();

或者,您可以准备一个字典而不是列表,其中字典键将是帐号。

创建一个类来存储所有帐户信息。阅读该行时,创建该类的实例并填写信息并存储在列表中。现在要比较名称和引脚,您只需使用 Linq 查询。

  Class AccountInfo
    {
     public int AccountNumber {get;set;}
     public string Name {get;set;}
     public int AtmPin {get;set;}
    public string Check {get;set;}
    public string Saving {get;set;}
    }
  //  Now in your Main program, use that class like this
    List<AccountInfo> accountInfoList= new List<AccountInfo>();
    foreach(string line in File.ReadAllLines("filename"))
    {
       AccountInfo ai =new AccountInfo();
      string[] split = line.Split('*');
            ai.AccountNumber = int.Parse(info [0]) ; 
            ai.Name = info [1] ; 
            ai.AtmPin = int.Parse(info [2]) ; 
            ai.Check = info [3] ; 
            ai.Saving = info [4] ; 
           accountInfoList.Add(ai);
    }
    // Some code to accept name and pin from user
    // Now compare name and pine like this
    var validationSuccessful = accountInfoList.Any(x=>x.AccountNumber==userEnteredAccountNumber &&
                        x.Name==userEnteredName &&
                        x.AtmPin==userEnteredPin);
    if(validationSuccessful)
    // Display next screen
    else
    // Display message log in failure

请记住,这是最简单的方法。我假设你正在做一些实践项目。真正的ATM项目将具有很高的安全性,并将使用Salt和Hash机制对Pin进行比较。它肯定会有一些数据库或服务。

正如 Jannik 所建议的那样,这就是在没有 Linq 查询的情况下进行比较的方式

bool validationSuccessful=false;
foreach(AccountInfo accountInfo in AccountInfoList)
{
  if(accountInfo.AccountNumber==userEnteredAccountNumber &&
                            accountInfo.Name==userEnteredName &&
                           accountInfo.AtmPin==userEnteredPin)
       {
        validationSuccessful = true;
         break;
       }
}

我希望您为帐户创建一个类,如下所示:

  public class Account
    {
        public int account { get; set; }
        public string name { get; set; }
        public int pin { get; set; }
        public string check { get; set; }
        public string saving { get; set; }
    }

然后形成一个帐户对象列表,其中包括存储帐户信息软件的文件中的所有帐户详细信息。迭代列表以检查是否有任何匹配的凭据软件可用。此完整方案的代码如下所示:

       List<Account> ATMAccountList = new List<Account>();
        foreach (var line in File.ReadAllLines("your Path Here"))
        {
            ATMAccountList.Add(linesplitter(line));
        }
         int accountNumberInput = 123, pinInput = 6565;
        // This will be the input values from the user
         bool matchFound = false;
        foreach (var accountItem in ATMAccountList)
        {
            if (accountItem.account == accountNumberInput && accountItem.pin == pinInput)
            {
                matchFound = true;
                break;
            }
        }
        if (matchFound)
        {
            //Proceed  with account
        }
        else
        {
            // display error ! in valid credential
        }          

其中方法linesplitter将定义为如下所示:

public Account linesplitter(string line)
    {
        Account AccountObject = new Account();
        string[] info = line.Split('*');
        AccountObject.account = int.Parse(info[0]);
        AccountObject.name = info[1];
        AccountObject.pin = int.Parse(info[2]);
        AccountObject.check = info[3];
        AccountObject.saving = info[4];
        return AccountObject;
    }

注意:

您可以使用 LINQ 执行相同的操作

        if (ATMAccountList.Where(x => x.account == accountNumberInput && x.pin == pinInput).Count() == 1)
        {
            //Proceed  with account
        }
        else
        {
            // display error ! in valid credentials
        }

这是一个基本的控制台应用程序,可能会给你一些想法。

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
    //private static XElement AccountData = new XElement("Root");
    private static DataSet dataSet = new DataSet();
    static void Main(string[] args)
    {
        DataSet dataSet = new DataSet();
        string[] readText = File.ReadAllLines(@"<Path to your account data file>'AccountData.txt");
        string strAccountNumber = string.Empty;
        string strPin = string.Empty;
        string strName = string.Empty;
        dataSet.ReadXml(new StringReader(new XElement("Root",
                            from str in readText
                            let fields = str.Split('*')
                            select new XElement("AccountData",
                                new XAttribute("AccountNo", fields[0]),
                                new XAttribute("Name", fields[1]),
                                new XAttribute("Pin", fields[2]),
                                new XAttribute("ChkBalance", fields[3]),
                                new XAttribute("SavBalance", fields[4])
                            )
                        ).ToString()));
        do
        {
            Console.WriteLine("Please enter your Account Number (press 'Q' to exit)");
            strAccountNumber = Console.ReadLine().ToLower();
            if (dataSet.Tables[0].Select(string.Format("AccountNo = '{0}'", strAccountNumber)).Count() == 1)
            {
                Console.WriteLine("Please enter your Pin");
                strPin = Console.ReadLine().ToLower();
                Console.WriteLine("Please enter your Name");
                strName = Console.ReadLine();
                if (dataSet.Tables[0].Select(string.Format("Pin = '{0}' AND Name = '{1}'", strPin, strName)).Count() == 1)
                {
                    DataRow[] result = dataSet.Tables[0].Select(string.Format("Pin = '{0}' AND Name = '{1}'", strPin, strName));
                    foreach (DataRow row in result)
                    {
                        Console.WriteLine(string.Format("Account Info for :: {0}", strName));
                        Console.WriteLine("{0}, {1}, {2}, {3}, {4}", row[0], row[1], row[2], row[3], row[4]);
                    }
                }
                else
                {
                    Console.WriteLine("Incorrect Details");
                }
            }
        } while (strAccountNumber != "q");
    }
}
}

不要忘记替换路径.....

string[] readText = File.ReadAllLines ....

与您的数据路径.....