Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate a string with blankspaces?

Tags:

c#

.net

asp.net

I need to create a 10-character string. If the string has less than 10 characters i need to append blank spaces till complete the entire 10-character string. I do the following but I have no succes, the result string has only one blank space concateneted in the end:

public void MyMethod(string[] mystrings)
{

    mystring[i].PadRight(10- mystrings[i].length)
    // Here I need a 10 char string. For example:
    // "1234567   "

}

Thank you.

like image 230
anmarti Avatar asked Dec 20 '22 04:12

anmarti


2 Answers

You could use String.PadRight:

mystring = mystring.PadRight(10, ' ');

(You can omit the second parameter, as in your case, when you use spaces).

Note however, that if mystring is already longer than 10 characters, it will remain longer. It is not clear from your question, if you need a string with exactly 10 characters length. If so, then do something like:

mystring = mystring.PadRight(10).Substring(0, 10);
like image 96
Christian.K Avatar answered Jan 01 '23 15:01

Christian.K


You can use string.Format with a custom format string:

mystring = string.Format("{0,-10}", mystring);
like image 39
Paolo Tedesco Avatar answered Jan 01 '23 17:01

Paolo Tedesco