在字符串的每一行上添加一个字符 [英] Add a character on each line of a string

查看:99
本文介绍了在字符串的每一行上添加一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个CSV转换器,为此,我需要将所有空格替换为;".我已经做了这一步.问题是我有一个带有多行mod的texbox.这是我的实际代码:

I make a CSV converter, for this, I need to replace all the spaces with ";". I have already did this step. The problem is that I have a texbox with the multiline mod. Here is my actual code :

string[] Espace1 = new string[] { " " };
foreach (string contenu in content1.Split(Espace1, StringSplitOptions.RemoveEmptyEntries))
{
    content1 = content1.Replace(" ", ";");
    File.WriteAllText(path1, content1);
}

以下是输出:(示例)

15;16;13;21
15;49;47
46;78;15

为了使文件能像csv一样很好地解释,我需要添加一个;"在每一行的末尾.喜欢:

So that the file is well interprets like a csv I need to add a ";" at the end of each line. Like :

15;16;13;21;
15;49;47;
46;78;15;

有什么帮助吗? :)

编辑

这是我完整的代码:

        string nom = tbxNom.Text;
        #region Normal
        try
        {
            string content1 = tbxArret.Text;
            string path1 = @"C:\Users\DanyWin\Desktop\CsvOutput\" + nom + ".csv";
            string[] Espace1 = new string[] { " " };
            foreach (string contenu in content1.Split(Espace1, StringSplitOptions.RemoveEmptyEntries))
            {
                content1 = content1.Replace(" ", ";");
                File.WriteAllText(path1, content1);
            }

        }
        catch
        {
            lblInfo.Text = "Erreur";
        }

推荐答案

content1似乎包含整个文件.

因此,如果要在每行中添加分号,则可以用分号和换行符代替换行符.

So if you want to add semicolons to each line, you could replace the newline with a semicolon and a newline.

content1 = content1.Replace("\n", ";\n");


您可以使代码更简单:


You can make your code a bit easier:

string nom = tbxNom.Text;
#region Normal
try
{
    string content1 = tbxArret.Text;
    string path1 = @"C:\Users\DanyWin\Desktop\CsvOutput\" + nom + ".csv";
    var lines = content1.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                .Select(line => Regex.Replace(line, @"\s+", ";") + ";");
    content1 = String.Join("\n", lines);
    File.WriteAllText(path1, content1);
}
catch
{
    lblInfo.Text = "Erreur";
}

这篇关于在字符串的每一行上添加一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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