Share via

String Format

Peter Volz 1,295 Reputation points
Jul 22, 2023, 1:00 PM

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.
11,338 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,799 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 120.4K Reputation points
    Jul 22, 2023, 1:13 PM

    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: Newest

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.