我想为每行大字符串添加前缀,不包括空行。下面的代码也为空行添加了前缀。我搜索了很多网站,但我无法找到合适的解决方案。这是我的代码:
string txt_input="abc \n \n efg \n \n \n hij";
string source = string.Join(Environment.NewLine, txt_input);
string result = string.Join(Environment.NewLine, source
.Split(new string[] { Environment.NewLine }, StringSplitOptions.None)
.Select(line => txt_prefix + line));
你的问题有点模糊,所以我会假设你的输入看起来像你提供的txt_input:
string txt_input="abc \n \n efg \n \n \n hij";
你想要一个排序的输出:
var ouput = "myPrefix_abc \n \n myPrefix_efg \n \n \n myPrefix_hij";"
这样的事情应该有效:
string prefix = "myPrefix_";
string txt_input="abc \n \n efg \n \n \n hij";
var split = txt_input.Split(new[] {"\n"}, StringSplitOptions.None);
var prefixedList = new List<string>();
foreach(var line in split){
if(string.IsNullOrWhiteSpace(line)) {
prefixedList.Add(line);
continue;
}
prefixedList.Add(prefix + line);
}
var output = string.Join("\n", prefixedList.ToArray());
Console.WriteLine(output);
如果你真的想看到\n
字符替换第二个最后一行
var output = string.Join("\\n", prefixedList.ToArray());
(注意'\ n'之前的第二个'\')