Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding whitespaces to a string in C#

Tags:

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 string.
E.g. if the passed string is 25 characters long, I want to add 5 more whitespaces.

The question is, how do I add whitespaces to a string?

like image 435
user1765862 Avatar asked Apr 06 '13 13:04

user1765862


People also ask

How do you add spaces to a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').

How do you put a space at the end of a string?

Use the str. ljust() method to add spaces to the end of a string, e.g. result = my_str. ljust(6, ' ') .

How do you put a space in a string in C?

Once the character is equal to New-line ('\n'), ^ (XOR Operator ) gives false to read the string. So we use “%[^\n]s” instead of “%s”. So to get a line of input with space we can go with scanf(“%[^\n]s”,str);

Does scanf skip whitespace?

This happens because scanf skips over white space when it reads numeric data such as the integers we are requesting here. White space characters are those characters that affect the spacing and format of characters on the screen, without printing anything visible.


2 Answers

You can use String.PadRight for this.

Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.

For example:

string paddedParam = param.PadRight(30); 
like image 126
D'Arcy Rittich Avatar answered Oct 23 '22 12:10

D'Arcy Rittich


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.

like image 22
Soner Gönül Avatar answered Oct 23 '22 11:10

Soner Gönül