Home > Mobile >  C#, I want to use a variable to sort characters using string interpolation
C#, I want to use a variable to sort characters using string interpolation

Time:01-27

I am sorry for the answerer who will suffer from my poor English skills.

static void function(int numSpace)
{
    Console.WriteLine($"{Convert.ToString(num, 16), numSpaces}); 
    .....
    .....
} 

I want to use the value of the 'numSpace' variable as a value that specifies how many spaces to space when sorting strings. The problem is that only constants are possible. I want to set this as a variable in the Main function to set the number of spaces to be spaced through keyboard input.

How could this be possible?

To solve this problem, I tested by referring to several materials posted on 'stack overflow', but all failed.

I wrote this code to make this possible.

const int num = numSpace;

But I found out that this doesn't work.

CodePudding user response:

Since what you need is basically nested string interpolation (since C# doesn't have dynamic or variable width implemented), but you have to use the original String.Format method since C# doesn't support nested interpolation directly:

Console.WriteLine(String.Format($"{{0,{numSpaces} }}", Convert.ToString(num, 16));

NOTE: The space after the close brace for interpolating numSpaces is required because of string interpolation using two close braces as an escape for a literal close brace. Fortunately format items ignore the space.

CodePudding user response:

The string interpolation feature is limited to padding to a fixed amount with whitespace only, so you'll have to pad yourself, remembering that a positive alignment right-justifies the string:

var padded = Convert.ToString(num, 16).PadLeft(numSpaces);
Console.WriteLine($"{padded}");  
  • Related