Search code examples
c#stringformatmessagemq

Custom format string


I am looking for some generic solution, so that I can generate the string. Like I want first 10 characters to be reserved for id, next 20 characters needs to reserved for name etc. but this character length my change. This requirement is for ibm mq message,. E.g.: if my id is 001, name is namexxxx and age 25 then my final string should look like:

001       namexxxx            25

Solution

  • Using String.PadRight you can achieve that. You can also pass these as parameters to a method, or read them from a configuration file or database:

    Console.WriteLine(id.PadRight(10) + name.PadRight(20) + age.PadRight(5));
    

    Another way would be to use String.Format but this one is a bit messier to parametrize:

    Console.WriteLine(String.Format("{0,-10}{1,-20}{2,-5}", id, name, age));
    

    Output in both cases:

    001       namexxxx            25