How to concatenate a string with spaces?

I need to create a 10 character string. If the string contains less than 10 characters, I need to add spaces before the completion of the entire 10-character string. I am doing the following, but I have no successful results, the result line contains only one empty space concatenated at the end:

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

Thanks.

+4
source share
7 answers

You can use String.PadRight :

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

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

Note that if a mystring already longer than 10 characters, it will stay longer. From your question it is not clear whether a string of exactly 10 characters is needed. If so, then do something like:

 mystring = mystring.PadRight(10).Substring(0, 10); 
+9
source

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

 mystring = string.Format("{0,-10}", mystring); 
+1
source

You need to use the string.PadRight method:

 string result = mystring.PadRight(10); 
+1
source

try it

  string str = "cc"; int charstoinsert = 10 - str.Length; for (int i = 0; i < charstoinsert; i++) { str += " "; } 
0
source

Try the following function

 #region GetPaddedString private string GetPaddedString(string strValue, int intLength) { string strReturn = string.Empty; string _strEmptySpace = " "; int _vinLength = strValue.Length; if (_vinLength < intLength) { strReturn = strValue + _strEmptySpace.PadRight((intLength - _vinLength)); } else { strReturn = strValue; } return strReturn; } #endregion GetPaddedString("test", 10) 
0
source

This should do the trick:

 str.PadRight(10, ' ').Substring(0, 10) 
0
source

try it

 string mystring= "sd"; while (mystring.Length <= 10) { mystring+= " "; } 
0
source

Source: https://habr.com/ru/post/1485414/


All Articles