Add a character on each line of a string

旧城冷巷雨未停 提交于 2019-12-04 04:53:47

问题


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

Here is the output : (an example)

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

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;

Any help ? :)

EDIT

Here is my complete code :

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

回答1:


content1 seems to contain the whole file.

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



回答2:


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

Remove all spaces then concat ";" at end




回答3:


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);

It's not the fastest solution, but it works.



来源:https://stackoverflow.com/questions/36044775/add-a-character-on-each-line-of-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!