tags:

views:

1253

answers:

9

For example, I have a txt file that reads:

12 345 45
2342 234 45 2 2 45345
234 546 34 3 45 65 765
12 23 434 34 56 76 5

I want to insert a comma between all the numbers, add a left brace to the begining of each line and a right brace to the end of each line. So after the editing it should read:

{12, 345, 45}
{2342, 234, 45, 2, 2, 45345}
{234, 546, 34, 3, 45, 65, 765}
{12, 23, 434, 34, 56, 76, 5}

How do I do it?

+1  A: 

You'll need to use the FileStream class to open the file, the StreamWriter class to read from the file, and the StreamWriter class to write back to the file.

You can create a FileStream like this:

FileStream file = new FileStream("FileName", FileMode.Open, FileAccess.ReadWrite);

Then wrap the FileStream in a StreamReader:

StreamReader reader = new StreamReader(file);

Then, read in each line and do your string processing (adding commas and brackets):

while(reader.EndOfFile)
{
   string currentLine = reader.ReadLine();
   // do your string processing here and save the result somewhere
}

Lastly, wrap the FileStream in a StreamWriter and write your modified strings back to the file:

StreamWriter writer = new StreamWriter(file);

// Write your content here
writer.Write("my content");

Don't forget to close your streams after working with them.

reader.Close();
writer.Close();
file.Close();
Donut
+2  A: 

Read each line.

Add a bracket before the string and after

Then replace space " " by ", " (comma and space)

waqasahmed
+5  A: 

you should work on the logic first instead of directly asking people to provide that for you. as for reading/writing a file, here you go:

//write      
FileStream fs = new FileStream("file_name", FileMode.Create);
StreamWriter w = new StreamWriter(fs, Encoding.UTF8);
w.WriteLine("text_to_write");
w.Flush();
w.Close();
fs.Close();

//read
fs = new FileStream("file_name", FileMode.Open);
StreamReader r = new StreamReader(fs, Encoding.UTF8);
Console.WriteLine(r.ReadLine());
r.Close();
fs.Close();
cw22
You should use using statements to ensure that objects (FileStreams, StreamReaders and StreamWriters are properly disposed of.
phsr
+1  A: 
  1. Load the whole file
  2. use string.split('\n') to divide the contents into lines
  3. use string.replace(' ',',') to insert commas.
  4. Save the file.

Or, as waqasahmed said, just do it one at a line.

See also: http://www.csharphelp.com/archives/archive24.html

Also, this sounds suspiciously like a homework problem. Maybe we should have a "homework" tag?

David Lively
+4  A: 

Something like this: (NOT TESTED)

string filename = @"c:\yourfilename.txt";
StringBuilder result = new StringBuilder();

            if (System.IO.File.Exists(filename))
            {
                using (StreamReader streamReader = new StreamReader(filename))
                {
                    String line;
                    while ((line = streamReader.ReadLine()) != null)
                    {
                        string newLine = String.Concat("{", line, "}", Environment.NewLine);
                        newLine = newLine.Replace(" ", ", ");
                        result.Append(newLine);
                    }
                }
            }

using (FileStream fileStream = new FileStream(filename , fileMode, fileAccess))
            {
                StreamWriter streamWriter = new StreamWriter(fileStream);
                streamWriter.Write(result);
                streamWriter.Close();
                fileStream.Close();
            }
Mark Redman
+1 for ensuring that objects are properly disposed of
phsr
+2  A: 

edit to add how to modify sLine. (not tested, but I'm pretty sure it'll work just fine)

    StreamReader sr = new StreamReader("path/to/file.txt");
    StreamWriter sw = new StreamWriter("path/to/outfile.txt");
    string sLine = sr.ReadLine();
    for (; sLine; sLine = sr.ReadLine() )
    {
        sLine = "{" + sLine.Replace(" ", ", ") + "}";
        sw.Write(sLine);
    }
jb
A: 

I pretty much figured it out while you were all giving me your answers, but thanks a lot anyway :). I came up with this:

TextReader reader = new StreamReader("triangle.txt");
TextWriter writer = new StreamWriter("triangle2.txt");
for (; ; )
{
    string s = reader.ReadLine();
    if (s == null)
       break;
    s = s.Replace(" ", ", ");
    s = "{" + s + "},";
    writer.WriteLine(s);
}
George Powell
Instead of an infinite for loop with a break, you should use a while loop like the following: while(reader.Peek() > -1)
phsr
I'd avoid infinite for(;;) loops; seems like bad style. You can simplify this as "while ((s=reader.Readline())!=null) { .... }
David Lively
+1  A: 
string [] lines = File.ReadAllLines("input.txt");
var processed = lines.Select(line => string.Format("{{{0}}}", line.Replace(" ", ", ")));
File.WriteAllLines("output.txt",processed.ToArray());
Mehmet Aras
+3  A: 

Added some LINQ for fun and profit (room for optimization ;) ):

System.IO.File.WriteAllLines(
    "outfilename.txt",
    System.IO.File.ReadAllLines("infilename.txt").Select(line =>
        "{" +
        string.Join(", ",
            line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
        ) + "}"
    ).ToArray()
);
aanund
All in a single statement! Unbeatable :-D
Tor Haugen