StringReader和StringWriter操作

iamzxf發表於2015-06-08


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace stringRWDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string strContent = "Welcome to the new world!\n" +
                "Wish you have a good day!\n"
                + "This is the end! ";

            Console.WriteLine("原始內容如下:");
            Console.WriteLine(strContent);

            string strLine, strP = null;
            StringReader strReader = new StringReader(strContent);

            while (true)
            {
                strLine = strReader.ReadLine();
                if (strLine != null)
                {
                    strP = strP + strLine.ToUpper() + "";
                }
                else
                {
                    strP = strP + "\n";
                    break;
                }
            }

            Console.WriteLine("修改後的內容:");
            Console.WriteLine(strP);

            int iCh;
            char convertedCh;
            StringWriter strWriter = new StringWriter();
            strReader = new StringReader(strP);
            bool flag = true;

            while (true)
            {
                iCh = strReader.Read();
                if (iCh == -1) break;
                convertedCh = Convert.ToChar(iCh);
                if (convertedCh == '!')
                {
                    strWriter.Write(convertedCh);
                    strWriter.Write("\n");
                    //strReader.Read();
                    //strReader.Read();
                    flag = true;
                }
                else
                {
                    if (flag)
                        strWriter.Write(convertedCh);
                    else
                        strWriter.Write(char.ToLower(convertedCh));
                    flag = false;
                }
            }

            Console.WriteLine("還原後的原始文字內容:");
            Console.WriteLine(strWriter.ToString());

            Console.ReadLine();

        }
    }
}



相關文章