Cut the last character of a C # string [duplicate]

2

I'm creating an export from SQL to TXT.

With this I add the ";" after building each column.

But at the end of the last column you are adding the ";" also.

How do I get this ";" the end of the last column of all lines?

My% of construction of rows and columns:

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        txt += row[column.ColumnName].ToString() + ";";
        int tamanho_linha = txt.Length;
        txt = Convert.ToString(tamanho_linha - 1);
     }

    txt += "\r\n";
}
    
asked by anonymous 13.04.2016 / 20:51

2 answers

2

Try to use Substring :

foreach (DataRow row in dt.Rows)
{
    foreach (DataColumn column in dt.Columns)
    {
        txt += row[column.ColumnName].ToString() + ";";
        txt = txt.Substring(0,txt.Length - 1);
    }
    txt += "\r\n";
}
    
13.04.2016 / 23:25
4

Do this:

foreach (DataRow row in dt.Rows) {
    foreach (DataColumn column in dt.Columns) {
        txt += row[column.ColumnName].ToString() + ";";
    }
    txt = txt.TrimEnd(";") + "\r\n";
}

Documentation for TrimEnd() .

I do not really recommend doing this. If you have more than 4 string concatenations, you should use StringBuilder to avoid the problem of Shlemiel the painter's algorithm . The algorithm as it stands is quadratic and can take much longer than expected by making unnecessary reallocations, also ending with the garbage collector.

var txt = new StringBuilder(); //se tiver uma estimativa de tamanho que ela terá, coloque aqui
foreach (DataRow row in dt.Rows) {
    foreach (DataColumn column in dt.Columns) {
        txt += row[column.ColumnName].ToString() + ";";
    }
    txt = txt.Remove(txt.Length - 1, 1); + "\r\n";
}

Compare the performance between the two.

    
13.04.2016 / 20:55