String Format

Peter Volz 1,095 Reputation points
2023-07-22T13:00:06.7633333+00:00

Hello

I have a string that can be 3 or 4 characters long, all I need to do is in case my string is 3 chars, add a single space in the beginning/end of my string, of course:

If string.Length = 3 Then string = " " + string
If string.Length = 3 Then string = string + " "

Just wonder if there's a string format syntax available to do the same? Thanks :)

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,950 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,500 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 109.9K Reputation points
    2023-07-22T13:13:23.1466667+00:00

    Check the examples:

    string s = "abc";
    
    string result1 = string.Format( "Result 1 = '{0,4}'", s );
    string result2 = string.Format( "Result 2 = '{0,-4}'", s );
    
    string result3 = $"Result 3 = '{s,4}'";
    string result4 = $"Result 4 = '{s,-4}'";
    
    string result5 = s.PadLeft( 4 );
    string result6 = s.PadRight( 4 );
    
    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful