如何在 C# 中读取和编辑 .txt 文件?
例如,我有一个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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
添加了一些 LINQ 以获取乐趣和利润(优化空间;)):
Added some LINQ for fun and profit (room for optimization ;) ):
像这样的东西:(未经测试)
Something like this: (NOT TESTED)
你应该首先研究逻辑,而不是直接要求人们为你提供逻辑。至于读/写文件,这里是:
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:
阅读每一行。
在字符串之前和之后添加括号
然后将空格“”替换为“,”(逗号和空格)
Read each line.
Add a bracket before the string and after
Then replace space " " by ", " (comma and space)
您需要使用
FileStream
类打开文件,StreamReader
类从文件读取,StreamWriter
类写回文件。您可以像这样创建一个
FileStream
:然后将
FileStream
包装在StreamReader
中:然后,读取每一行并进行字符串处理(添加逗号和括号):
最后,将
FileStream
包装在StreamWriter
中,并将修改后的字符串写回到文件中:使用完流后不要忘记关闭它们。
You'll need to use the
FileStream
class to open the file, theStreamReader
class to read from the file, and theStreamWriter
class to write back to the file.You can create a
FileStream
like this:Then wrap the
FileStream
in aStreamReader
:Then, read in each line and do your string processing (adding commas and brackets):
Lastly, wrap the
FileStream
in aStreamWriter
and write your modified strings back to the file:Don't forget to close your streams after working with them.
编辑添加如何修改 sLine。 (未经测试,但我很确定它会工作得很好)
edit to add how to modify sLine. (not tested, but I'm pretty sure it'll work just fine)
或者,正如瓦卡萨麦德所说,一行一行地做一个。
另请参阅:http://www.csharphelp.com/archives/archive24.html
而且,这听起来很像一个家庭作业问题。也许我们应该有一个“作业”标签?
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?
最后我使用了第二个文件而不是编辑第一个文件:
In the end I used a second file rather than editing the first: