我有一根绳子。
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
我需要在字符串中每次出现“@”符号后添加换行符。
我的输出应该像这样
fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
我有一根绳子。
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
我需要在字符串中每次出现“@”符号后添加换行符。
我的输出应该像这样
fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
当前回答
正如其他人所说,new line char将在windows中的文本文件中为您提供新行。 试试下面的方法:
using System;
using System.IO;
static class Program
{
static void Main()
{
WriteToFile
(
@"C:\test.txt",
"fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@",
"@"
);
/*
output in test.txt in windows =
fkdfdsfdflkdkfk@
dfsdfjk72388389@
kdkfkdfkkl@
jkdjkfjd@
jjjk@
*/
}
public static void WriteToFile(string filename, string text, string newLineDelim)
{
bool equal = Environment.NewLine == "\r\n";
//Environment.NewLine == \r\n = True
Console.WriteLine("Environment.NewLine == \\r\\n = {0}", equal);
//replace newLineDelim with newLineDelim + a new line
//trim to get rid of any new lines chars at the end of the file
string filetext = text.Replace(newLineDelim, newLineDelim + Environment.NewLine).Trim();
using (StreamWriter sw = new StreamWriter(File.OpenWrite(filename)))
{
sw.Write(filetext);
}
}
}
其他回答
前面的答案很接近,但为了满足@符号保持接近的实际要求,您希望它是str.Replace("@", "@" + System.Environment.NewLine)。这将保留@符号,并为当前平台添加适当的换行符。
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
var result = strToProcess.Replace("@", "@ \r\n");
Console.WriteLine(result);
输出
string str = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
str = str.Replace("@", Environment.NewLine);
richTextBox1.Text = str;
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
strToProcess.Replace("@", Environment.NewLine);
Console.WriteLine(strToProcess);
}
}
然后将之前的答案修改为:
Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));
如果您不希望文本文件中出现换行符,那么就不要保存它。