簡體   English   中英

c#從文本文件中拆分整數和字符串,並將它們添加到兩個不同的列表框中

[英]c# split integers and strings from text file and add them to two different listbox

我正在嘗試從文本文件中解析銷售信息,並將其放入兩個列表框

文本文件包含以下信息:

Sam West $10,000.00
Mae West $125,900.00
North West $2,000.00
Michelle Smith $25,000.00
John Smith $12,500.00
Martin Smith $19,900.00
David Sampson $32,500.00
Joan Sampson $5,990.00
Sam Sampson $10,000.00
Mae Sampson $125,500.00
North Sampson $2,000.00
Michelle West $25,000.00
John Johnson $12,500.00
Martin Johnson $19,900.00
David Johnson $32,500.00
Joan Johnson $5,990.00
Sam Hartmann $10,000.00
Mae Hartmann $125,100.00
North Hartmann $2,000.00
Michelle Hartmann $25,000.00
John Johnson $12,500.00
Martin Hartmann $19,900.00
David Hartmann $32,500.00
Joan Hartmann $5,990.00

我的代碼在這里

private void btnReadInSalesData_Click(object sender, EventArgs e)
{
    StreamReader reader = new StreamReader("SalesNumbers.txt");
    List<int> numbers = new List<int>();
    int intTotal = 0;

    while (!reader.EndOfStream)
    {
        string line = reader.ReadLine();
        string[] tokens = line.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);

        foreach (string s in tokens)
        {
            if (int.TryParse(s, out intTotal))
                numbers.Add(intTotal);
            lstTotalSales.Items.Add(s);
        }
    }

這是輸出的圖片http://s24.postimg.org/ylm8vl9at/output.jpg

我只是想讀取文本文件,然后將總銷售額添加到lstTotalSales列表框中,並將“全名”添加到lstNames列表框中。

謝謝

您應該使用decimal而不是int ,因為您的數字不是整數。

您還應該在循環中更改邏輯。 我認為應該更像這樣:

foreach (string s in tokens)
{
    if (decimal.TryParse(s, out decTotal))
    {
        numbers.Add(decTotal);
        lstTotalSales.Items.Add(s);
    }
    else
    {
        lstNames.Items.Add(s);
    }
}

您錯過了將每一行拆分為名稱和值。

嘗試這個:

        string[] lines = File.ReadAllLines("SalesNumbers.txt");
        foreach (string line in lines) {
            string[] s = line.Split("$".ToCharArray());
            if (s.Length<2) { /* */ }
            double d;
            if (!double.TryParse(s[1], NumberStyles.Float, CultureInfo.CurrentCulture, out d)) {                
                // Handle if not a number
            }
            lstNames.Items.Add(s[0]);
            lstTotalSales.Items.Add(d);
        }

編輯

當我們將值轉換為雙精度時,在顯示值時必須添加貨幣符號:

string text = "$" + value.ToString();

請注意,我們暗示總是用$符號分割。

假設有多個貨幣符號,則必須跟蹤拆分符號:

string currencySymbols = "$€Y";
//...
int index = line.IndexOfAny(currencySymbols.ToCharArray());
if (index<0) {} //Nothing found
char usedSymbol = line[index];            // <- found symbol
string name = line.Substring(0, index);
string value = line.Substring(index+1);
//...

暫無
暫無

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

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