Home [C# 筆記][File] 工資翻倍-練習
Post
Cancel

[C# 筆記][File] 工資翻倍-練習

案例

1
2
3
4
對職員工資文件處理,所有人的工資加倍然後輸出到新文件。    
文件案例:    
Ken|3000
Vic|50000
技術要點:
  • 使用 ReadAllLines,因為要一行一行的讀取數據。
  • 使用 WriteAllLines,因為要一行一行的寫入。
  • 使用 .Split分割,並通過第二個參數 RemoveEmptyEntries 去掉空白,以取得數字做工資翻倍。
  • 使用 string.Join 或自行組字串,組裝原來的格式回去(|分隔)。
程式碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//因為要一行一行的讀,所以用ReadAllLines,返回的是字串陣列,所以要宣告string[]來接
string[] str = File.ReadAllLines(@"C:\Users\rivalin\Desktop\工資.txt");
//要拿到數字
for (int i = 0; i < str.Length; i++)
{

    //Ken|3000,要拿到數字,用Split分割,並去掉空白RemoveEmptyEntries
    string[] strNew = str[i].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
    int salary = Convert.ToInt32(strNew[1]) * 2;//工資翻倍
    str[i] = $"{strNew[0]}|{salary}"; //組字串回去
    //str[i] = string.Join("|", new string[] { strNew[0], salary.ToString() }); //string.Join組回去
}
//寫入txt
File.WriteAllLines(@"C:\Users\rivalin\Desktop\工資.txt", str);
Console.WriteLine("done.");
Console.ReadKey();
This post is licensed under CC BY 4.0 by the author.