Dart String padRight()
Syntax & Examples
Syntax of String.padRight()
The syntax of String.padRight() method is:
String padRight(int width, [String padding = ' '])
This padRight() method of String pads this string on the right if it is shorter than width
.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
width | required | the total width to pad the string to |
padding | optional [default value is ' '] | the padding character used for padding (default is space) |
Return Type
String.padRight() returns value of type String
.
✐ Examples
1 Pad to Total Width
In this example,
- We have a string
str
with the value 'Hello'. - We use the
padRight()
method to pad the string to a total width of 10 characters. - Since the length of 'Hello' is less than 10, it gets padded with spaces on the right.
- We print the padded string to standard output.
Dart Program
void main() {
String str = 'Hello';
String paddedStr = str.padRight(10);
print('Padded string: $paddedStr');
}
Output
Padded string: Hello
2 Pad with Custom Padding Character
In this example,
- We have a string
str
with the value 'ABC'. - We use the
padRight()
method to pad the string to a total width of 5 characters, using '-' as the padding character. - Since the length of 'ABC' is less than 5, it gets padded with '-' on the right.
- We print the padded string to standard output.
Dart Program
void main() {
String str = 'ABC';
String paddedStr = str.padRight(5, '-');
print('Padded string: $paddedStr');
}
Output
Padded string: ABC--
3 Pad with Custom Padding Character and Total Width
In this example,
- We have a string
str
with the value 'Lorem ipsum'. - We use the
padRight()
method to pad the string to a total width of 15 characters, using '*' as the padding character. - Since the length of 'Lorem ipsum' is less than 15, it gets padded with '*' on the right.
- We print the padded string to standard output.
Dart Program
void main() {
String str = 'Lorem ipsum';
String paddedStr = str.padRight(15, '*');
print('Padded string: $paddedStr');
}
Output
Padded string: Lorem ipsum****
Summary
In this Dart tutorial, we learned about padRight() method of String: the syntax and few working examples with output and detailed explanation for each example.