在字符串的每一行上添加一个字符

时间:2016-03-16 19:03:34

标签: c# character line add

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

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我需要添加&#34 ;;"在每一行的末尾。喜欢:

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";
        }

3 个答案:

答案 0 :(得分:3)

content1似乎包含整个文件。

因此,如果要为每行添加分号,可以用分号和换行符替换换行符。

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

您可以使代码更容易:

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";
}

答案 1 :(得分:0)

content1 = string.Concat( content1.Replace(" ", ";"), ";");

删除所有空格然后连续";"在结束

答案 2 :(得分:0)

char []split = new char[]{' '};

//replaces all " " with ";", contiguous "    " will be replaced with a single ";"
var c2 = String.Join(";", content1.Split(split, StringSplitOptions.RemoveEmptyEntries)); 

//replaces all newlines with a semicolon followed by a newline, thus appends a semicolon to the end of line. 
var c3 = c2.Replace(System.Environment.NewLine, ";"+System.Environment.NewLine);

//If the file did not end with an NewLine, append a semicolon to the last line
if (!c3.EndsWith(System.Environment.NewLine)) c3+=";";

File.WriteAllText(path, c3);

这不是最快的解决方案,但它确实有效。