fillSpaceStr static method

List<String> fillSpaceStr(
  1. List<String> strs
)

填充字符串数组,使每个字符串长度相同(前后补空格)

传入字符串列表 strs,将各字符串通过前后补空格的方式填充至最大长度,实际内容两端对齐。

示例:

List<String> input = ['a', 'abc', 'bb'];
List<String> filled = CommonUtil.fillSpaceStr(input);
print(filled); // [' a ', 'abc', 'bb ']

返回值: 返回一个各项填充长度至一致的新字符串数组。

Implementation

static List<String> fillSpaceStr(List<String> strs) {
  if (strs.isEmpty) return strs;

  // 获取最长字符串的长度
  int maxLength = strs.map((str) => str.length).reduce(max);

  // 遍历处理每个字符串
  List<String> result = strs.map((str) {
    if (str.length == maxLength) return str;

    // 计算需要补充的空格数量
    int spacesToAdd = maxLength - str.length;
    // 如果是奇数,后面多加一个空格
    int frontSpaces = spacesToAdd ~/ 2;
    int backSpaces = spacesToAdd - frontSpaces;

    // 在字符串前后添加空格
    return '${' ' * frontSpaces}$str${' ' * backSpaces}';
  }).toList();

  return result;
}