Cut the last character of a string C#

Asked

Viewed 5,403 times

2

I’m creating an export from SQL for the TXT.

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

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

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

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

2 answers

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 of TrimEnd().

I don’t really recommend doing this. If you have more than 4 concatenations of string, must use StringBuilder, to avoid the problem of Shlemiel the Painter’s Algorithm. The algorithm as it is is quadratic and can take much longer than expected by making needless relocations, also ending 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";
}

I put in the Github for future reference.

Compare the performance between the two.

  • Thanks @bigown, it worked.

2


Try to use the 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";
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.