wrapString method

String wrapString({
  1. int wordCount = 1,
  2. bool wrapEach = false,
  3. String delimiter = '\n',
})

Wraps the string based on the specified word count, wrap behavior, and delimiter. Example: "This is a test".wrapString(wrapCount: 2, wrapEach: false) => "This is\na test"

Implementation

String wrapString({
  int wordCount = 1,
  bool wrapEach = false,
  String delimiter = '\n',
}) {
  if (isEmptyOrNull) return '';
  final wrapCount = wordCount <= 0 ? 1 : wordCount;
  // Handling strings with multiple consecutive spaces by reducing them to single spaces.
  final words = this!.trim().replaceAll(RegExp(' +'), ' ').split(' ');
  if (words.isEmpty) return '';
  final buffer = StringBuffer();

  if (wrapEach) {
    for (var i = 0; i < words.length; i++) {
      buffer.write(words[i]);
      if ((i + 1) % wrapCount == 0 && i != words.length - 1) {
        buffer.write(delimiter);
      } else if (i != words.length - 1) {
        buffer.write(' ');
      }
    }
  } else {
    for (var i = 0; i < words.length; i++) {
      buffer.write(words[i]);
      if (i == wrapCount - 1 && words.length > wrapCount) {
        buffer.write(delimiter);
      } else if (i != words.length - 1) {
        buffer.write(' ');
      }
    }
  }

  return buffer.toString();
}