如何在 C# 中读取和编辑 .txt 文件?

发布于 2024-08-03 14:10:00 字数 335 浏览 6 评论 0原文

例如,我有一个txt文件,内容如下:

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

我想在所有数字之间插入逗号,在每行的开头添加一个左大括号,在每行的末尾添加一个右大括号。因此,编辑后应该显示:

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

我该如何做?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

青春有你 2024-08-10 14:10:00

添加了一些 LINQ 以获取乐趣和利润(优化空间;)):

System.IO.File.WriteAllLines(
    "outfilename.txt",
    System.IO.File.ReadAllLines("infilename.txt").Select(line =>
        "{" +
        string.Join(", ",
            line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)
        ) + "}"
    ).ToArray()
);

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()
);
和影子一齐双人舞 2024-08-10 14:10:00

像这样的东西:(未经测试)

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();
            }

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();
            }
断肠人 2024-08-10 14:10:00

你应该首先研究逻辑,而不是直接要求人们为你提供逻辑。至于读/写文件,这里是:

//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();

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();
氛圍 2024-08-10 14:10:00

阅读每一行。

在字符串之前和之后添加括号

然后将空格“”替换为“,”(逗号和空格)

Read each line.

Add a bracket before the string and after

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

陌伤浅笑 2024-08-10 14:10:00
string [] lines = File.ReadAllLines("input.txt");
var processed = lines.Select(line => string.Format("{{{0}}}", line.Replace(" ", ", ")));
File.WriteAllLines("output.txt",processed.ToArray());
string [] lines = File.ReadAllLines("input.txt");
var processed = lines.Select(line => string.Format("{{{0}}}", line.Replace(" ", ", ")));
File.WriteAllLines("output.txt",processed.ToArray());
凹づ凸ル 2024-08-10 14:10:00

您需要使用 FileStream 类打开文件,StreamReader 类从文件读取,StreamWriter 类写回文件。

您可以像这样创建一个 FileStream

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

然后将 FileStream 包装在 StreamReader 中:

StreamReader reader = new StreamReader(file);

然后,读取每一行并进行字符串处理(添加逗号和括号):

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

最后,将 FileStream 包装在 StreamWriter 中,并将修改后的字符串写回到文件中:

StreamWriter writer = new StreamWriter(file);

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

使用完流后不要忘记关闭它们。

reader.Close();
writer.Close();
file.Close();

You'll need to use the FileStream class to open the file, the StreamReader 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();
静赏你的温柔 2024-08-10 14:10:00

编辑添加如何修改 sLine。 (未经测试,但我很确定它会工作得很好)

    StreamReader sr = new StreamReader("path/to/file.txt");
    StreamWriter sw = new StreamWriter("path/to/outfile.txt");
    string sLine = sr.ReadLine();
    for (; sLine != null; sLine = sr.ReadLine() )
    {
        sLine = "{" + sLine.Replace(" ", ", ") + "}";
        sw.WriteLine(sLine);
    }

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 != null; sLine = sr.ReadLine() )
    {
        sLine = "{" + sLine.Replace(" ", ", ") + "}";
        sw.WriteLine(sLine);
    }
饭团 2024-08-10 14:10:00
  1. 加载整个文件,
  2. 使用 string.split('\n') 将内容分成行,
  3. 使用 string.replace(' ',',') 插入逗号。
  4. 保存文件。

或者,正如瓦卡萨麦德所说,一行一行地做一个。

另请参阅:http://www.csharphelp.com/archives/archive24.html

而且,这听起来很像一个家庭作业问题。也许我们应该有一个“作业”标签?

  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?

秋叶绚丽 2024-08-10 14:10:00

最后我使用了第二个文件而不是编辑第一个文件:

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);
}

In the end I used a second file rather than editing the first:

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文