如何将所有字符串追加到空的新行? [英] How to Append All String up to empty new line?

查看:104
本文介绍了如何将所有字符串追加到空的新行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在尝试将文本追加到空/空新行来吗?



我的txt文件是:



ABC

D



EF

G



接受输出:

ABCD

EFG

Hi i'm trying to append the text up to empty/null new line come?

my txt file is:

ABC
D

EF
G

Accetpted output:
ABCD
EFG

推荐答案

Linq解决方案:

Linq solution:
string[] filecontent = File.ReadAllLines(@"FullTextFileName");
var lines = filecontent.Where(x=>!string.IsNullOrWhiteSpace(x)).Select(x=>x);







注意:OriginalGriff [ ^ ]提到(在问题的评论中)上面的代码不会消除空白行。我测试了它,它工作正常。如果上面的代码有问题,请告诉我。我想知道文本编码。这可能是麻烦的原因。



谢谢你,OriginalGriff,指出我想要获得特定的输出。



这是一个想法:




Note: OriginalGriff[^] mentioned (in the comment to the question) that above code does not eliminate blank lines. I tested it and it works fine. Please, let me know if there is a problem with above code. I'm wondering about text coding. It might be the reason of troubles.

Thank you, OriginalGriff, for pointing me that OP wanted to get specific output.

Here is an idea:

string[] filecontent = { "ABC", "D", "", "EF", "G", "", "HIJ", "K", "LM"};
var lines = filecontent.Where(x=>!string.IsNullOrEmpty(x))
            .Select((x, ind) => new{line=(string)x, index=(int)ind+1})
            .Aggregate("", (a, b) => a += (((b.index+1) % 2==0) ? " " : "") + b.line).Split(' ').Skip(1);





结果:



Result:

ABCD
EFG
HIJK
LM


尝试:

Try:
string[] inp = { "ABC", "D", "", "EF", "G" };
List<string> outp = new List<string>();
StringBuilder sb = new StringBuilder();
foreach (string s in inp)
    {
    if (string.IsNullOrWhiteSpace(s))
        {
        if (sb.Length > 0) outp.Add(sb.ToString());
        sb = new StringBuilder();
        }
    else
        {
        sb.Append(s);
        }
    }
if (sb.Length > 0) outp.Add(sb.ToString());</string></string>


这篇关于如何将所有字符串追加到空的新行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆