如何 read/append 在 C# 中使用精确的 spacing/tabs/lines 字符串
How to read/append string in C# with exact spacing/tabs/lines
我有样本数据
string test = @"allprojects {
repositories {
test()
}
}"
当我阅读 test
时,我应该得到带有 spaces/tabs/new 行的确切字符串,而不是在需要换行的地方写 Environment.NewLine
等。当我打印时,它应该打印相同的格式 [WYSIWYG] 类型。
目前它在调试器中给出类似的东西allprojects {\r\n\t\t repositories { \r\n\t\t test() \r\n\t\t } \r\n\t\t }
有几种方法可以确定换行,这取决于您使用的OS:
- Windows:
\r\n
- Unix:
\n
- Mac:
\r
至于标签,你只需要\t
。
因此,在您的字符串中,您只需要:
string test = @"allprojects {\r\n\trepositories {\r\n\t\ttest()\r\n\t}\r\n}"
将输出:
allprojects {
repositories {
test()
}
}
我在需要这个的字符串文字中所做的只是根本不缩进内容:
namespace Foo {
class Bar {
const string test = @"
allprojects {
repositories {
test()
}
}";
}
}
并去掉最初的换行符。看起来有点难看,但它确实说明了前导空格很重要。
您也可以第二次放置 @"
,但自动代码格式化可能会移动它,它看起来与实际文本不太接近。 (代码格式不应触及字符串的内容,但我不能保证。)
如果逐行处理字符串,这应该正确往返,无论如何看起来都是合适的:
var reader = new StringReader(test);
reader.ReadLine();
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
Console.ReadLine();
或者只是从文件/资源中读取它们。
我有样本数据
string test = @"allprojects {
repositories {
test()
}
}"
当我阅读 test
时,我应该得到带有 spaces/tabs/new 行的确切字符串,而不是在需要换行的地方写 Environment.NewLine
等。当我打印时,它应该打印相同的格式 [WYSIWYG] 类型。
目前它在调试器中给出类似的东西allprojects {\r\n\t\t repositories { \r\n\t\t test() \r\n\t\t } \r\n\t\t }
有几种方法可以确定换行,这取决于您使用的OS:
- Windows:
\r\n
- Unix:
\n
- Mac:
\r
至于标签,你只需要\t
。
因此,在您的字符串中,您只需要:
string test = @"allprojects {\r\n\trepositories {\r\n\t\ttest()\r\n\t}\r\n}"
将输出:
allprojects {
repositories {
test()
}
}
我在需要这个的字符串文字中所做的只是根本不缩进内容:
namespace Foo {
class Bar {
const string test = @"
allprojects {
repositories {
test()
}
}";
}
}
并去掉最初的换行符。看起来有点难看,但它确实说明了前导空格很重要。
您也可以第二次放置 @"
,但自动代码格式化可能会移动它,它看起来与实际文本不太接近。 (代码格式不应触及字符串的内容,但我不能保证。)
如果逐行处理字符串,这应该正确往返,无论如何看起来都是合适的:
var reader = new StringReader(test);
reader.ReadLine();
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine(line);
}
Console.ReadLine();
或者只是从文件/资源中读取它们。