【发布时间】:2011-02-20 18:30:16
【问题描述】:
我喜欢阅读检查文本是否有多行或单行,然后我将阅读多行并转换为单行我该怎么做?
【问题讨论】:
-
在这种情况下什么是多行?
我喜欢阅读检查文本是否有多行或单行,然后我将阅读多行并转换为单行我该怎么做?
【问题讨论】:
您真的不需要检查,因为File.ReadAllLines() 将始终返回一个字符串数组,而不管行数如何。您可以利用该行为,只需将返回的数组与您选择的分隔符连接起来。
string singleLine = string.Join(" ", File.ReadAllLines("filepath"));
【讨论】:
string text = String.Empty;
if(textbox.Text.Contains(Environment.NewLine))
{
//textbox contains a new line, replace new lines with spaces
text = textbox.Text.Replace(Environment.NewLine, " ");
}
else
{
//single line - simply assign to variable
text = textbox.Text;
}
【讨论】:
尝试类似的方法(取决于你如何对待“线条”):
System.IO.File.ReadAllText(path).Replace("\n\r", "");
【讨论】:
"\r\n"。但更好的是Environment.NewLine
这将从文本文件中读取所有行并将它们连接成一个字符串;作为分隔符:
string[] lines = File.ReadAllLines("myfile.txt");
string myLine = String.Join(";", lines);
【讨论】: