Adding whitespaces to a string in C#

前端 未结 4 1679
失恋的感觉
失恋的感觉 2021-01-03 21:58

I\'m getting a string as a parameter.

Every string should take 30 characters and after I check its length I want to add whitespaces to the end of the st

4条回答
  •  醉梦人生
    2021-01-03 22:22

    You can use String.PadRight method for this;

    Returns a new string of a specified length in which the end of the current string is padded with spaces or with a specified Unicode character.

    string s = "cat".PadRight(10);
    string s2 = "poodle".PadRight(10);
    
    Console.Write(s);
    Console.WriteLine("feline");
    Console.Write(s2);
    Console.WriteLine("canine");
    

    Output will be;

    cat       feline
    poodle    canine
    

    Here is a DEMO.

    PadRight adds spaces to the right of strings. It makes text easier to read or store in databases. Padding a string adds whitespace or other characters to the beginning or end. PadRight supports any character for padding, not just a space.

提交回复
热议问题