简体   繁体   English

写入新文本文件时替换StreamWriter

[英]StreamWriter Replace while Writing to a new Text File

Is there any possible way to replace a character with a string, like to say replace '\\x0A' with "\\r\\n" for example. 有没有可能用字符串替换字符的方法,例如说用'\\x0A' "\\r\\n" '\\x0A'替换'\\x0A' This is my code and I honestly can't find a way to put it in, not to mention that the Replace function does not allow String.Replace(Char, String) or String.Replace(String, Char) 这是我的代码,老实说我找不到方法,更不用说Replace函数不允许String.Replace(Char, String)String.Replace(String, Char)

StreamWriter wwrite = new StreamWriter(sfd.FileName, false, Encoding.GetEncoding("EUC-JP"));
for (int i = 0; i < listView1.Items.Count; ++i)
{
    wwrite.WriteLine((i + 1).ToString() + "^" + listView1.Items[i].SubItems[3].Text);
}
wwrite.Close();

You can replace a character with a string by simply converting the character to a string and then calling the Replace(string, string) overload. 您可以通过简单地将字符转换为字符串,然后调用Replace(string, string)重载来用字符串Replace(string, string) For instance: 例如:

wwrite.WriteLine((i + 1).ToString() + "^" + listView1.Items[i].SubItems[3].Text.Replace("\x0A", "\r\n"));

You seem to be confused about strings. 您似乎对字符串感到困惑。 Strings are simply a collection of characters. 字符串只是字符的集合。 So "\\n" and '\\n' are essentially the same value. 因此, "\\n"'\\n'本质上是相同的值。 The first stores the value as a single character string and the second stores the same value as a character. 第一个将值存储为单个字符串,第二个将相同的值存储为字符。 If you want to replace a new-line character with the actual string \\n (as two separate characters), you need to escape the backslash, for instance: 如果要将换行符替换为实际的字符串\\n (作为两个单独的字符),则需要转义反斜杠,例如:

s = s.Replace("\n", "\\n");

Or: 要么:

s = s.Replace("\n", @"\n");

用Google 搜寻 StreamReader和StreamWriter并发现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM