我有一个字符串.
string strToProcess = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
我需要在字符串中每次出现"@"符号后添加换行符.
我的输出应该是这样的
fkdfdsfdflkdkfk@ dfsdfjk72388389@ kdkfkdfkkl@ jkdjkfjd@ jjjk@
CMS.. 457
string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@"; text = text.Replace("@", "@" + System.Environment.NewLine);
Jason.. 65
你可以在@符号之后添加一个换行符,如下所示:
string newString = oldString.Replace("@", "@\n");
您还可以NewLine
在Environment
类中使用该属性(我认为它是环境).
string text = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@"; text = text.Replace("@", "@" + System.Environment.NewLine);
你可以在@符号之后添加一个换行符,如下所示:
string newString = oldString.Replace("@", "@\n");
您还可以NewLine
在Environment
类中使用该属性(我认为它是环境).
之前的答案很接近,但为了满足@
符号保持接近的实际要求,您需要这样做str.Replace("@", "@" + System.Environment.NewLine)
.这将保留@
符号并为当前平台添加适当的换行符.
然后只需修改以前的答案:
Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));
如果您不想在文本文件中添加换行符,则不要保留它.
一个简单的字符串替换将完成这项工作.看看下面的示例程序:
using System; namespace NewLineThingy { class Program { static void Main(string[] args) { string str = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@"; str = str.Replace("@", "@" + Environment.NewLine); Console.WriteLine(str); Console.ReadKey(); } } }
正如其他人所说的那样,新行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); } } }