center method

String center(
  1. int length, [
  2. String character = ' '
])

Return a String of specified length width which is align in center, using the specified character.

The default value of character is space ' '.

Example :

print('this'.center(6)); // ' this ';
print('this'.center(7,'0')); // '00this0'

Throws an AssertionError if character's length is greater than 1.

Implementation

String center(int length, [String character = ' ']) {
  assert(character.length <= 1, "character's length should be equal to 1");

  final StringBuffer str = StringBuffer();
  final int len = length - this.length;

  final int times = len ~/ 2;

  str.writeAll([
    len.isOdd ? character * (times + 1) : character * times,
    this,
    character * times,
  ]);

  return len.isNegative ? this : str.toString();
}