Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

filestream - How to read character in a file 1 by 1 c#

I want my program to read a text file all characters 1 by 1 and whereever it finds a double-quote ("), it adds a semicolon before that inverted comma. For eg we have a paragraph in a text file as follow:

This is a paragraph which conains lots and lots of characters and some names and dates. My name "Sam" i was born at "12:00" "noon". I live in "anyplace" .

Now I want the output to be as follows:

This is a paragraph which conains lots and lots of characters and some names and dates. My name ;"Sam;" i was born at ;"12:00;" ;"noon;". I live in ;"anyplace;" .

It should open the file using file stream then reads character and then adds semicolon where it finds quotes. And the output should be equal to textbox1.Text.

This is my code:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            
            char ch;
            int Tchar = 0;
            StreamReader reader;
            reader = new StreamReader(@"C:Usersuser1Documentsdata.txt");
            do
            {
                ch = (char)reader.Read();
                Console.Write(ch);
                if (Convert.ToInt32(ch) == 34)
                {
                    Console.Write(@";");
                }
                Tchar++;
            } while (!reader.EndOfStream);
            reader.Close();
            reader.Dispose();
            Console.WriteLine(" ");
            Console.WriteLine(Tchar.ToString() + " characters");
            Console.ReadLine();
        }
    }
}

This is the output:

This is a paragraph which conains lots and lots of characters and some names and dates. My name ";Sam"; i was born at ";12:00"; ";noon";. I live in ";anyplace"; . 154 characters

I want that semicolon before the quotes. Any help would be appreciated. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Swap the order of the operations:

    if (Convert.ToInt32(ch) == 34)
    {
        Console.Write(@";");
    }
    Console.Write(ch);

e.g. don't write the original character until AFTER you've decided to output a semicolon or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...