Lập trình C# -  Đếm số từ trong file

 Đếm số từ trong file

Viết chương trình C# để đếm số từ được lưu giữ trong một file.

Chương trình C#

Dưới đây là chương trình C# minh họa lời giải cho bài tập đếm số từ trong file trong C#. Bạn cần sử dụng System.IO namespace cho hoạt động đọc ghi file.

using System;
using System.IO;

namespace Csharp
{
    class TestCsharp
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\nChuong trinh C# de Dem so tu trong File:");
            Console.WriteLine("-------------------------------------------\n");
            StreamReader file = File.OpenText("test.txt");
            string line;
            int amountOfWords = 0;
            do
            {
                line = file.ReadLine();
                if (line != null)
                {
                    string[] words = line.Split(' ');
                    amountOfWords += words.Length;
                }
            }
            while (line != null);
            file.Close();
            Console.WriteLine("Tong so tu co trong test.txt la: " + amountOfWords);

            Console.ReadKey();
        }
    }
}

Kết quả chương trình C#

Giả sử, nội dung của test.txt như sau: (đã tạo trong các bài tập trước)

Ghi file trong C#

Biên dịch và chạy chương trình C# trên sẽ cho kết quả:

Đếm số từ trong file trong C#