upperCaseLettersOnly method

String upperCaseLettersOnly()

Extracts and concatenates only the uppercase letters from the string.

This method iterates through the runes of the string and checks if each character is an uppercase letter. If it is, the character is appended to the result.

Performance: Uses StringBuffer for O(n) time complexity instead of string concatenation which would be O(n²).

Returns: A new string containing only the uppercase letters from the original string.

Example:

'Ben Bright 1234'.upperCaseLettersOnly(); // Returns 'BB'
'UPPERCASE'.upperCaseLettersOnly();       // Returns 'UPPERCASE'
'lowercase'.upperCaseLettersOnly();       // Returns ''
''.upperCaseLettersOnly();                // Returns ''

Implementation

String upperCaseLettersOnly() {
  if (isEmpty) {
    return '';
  }

  // Use StringBuffer for O(n) performance instead of O(n²) string concatenation
  final StringBuffer buffer = StringBuffer();

  // https://stackoverflow.com/questions/9286885/how-to-iterate-over-a-string-char-by-char-in-dart
  for (final int rune in runes) {
    final String c = String.fromCharCode(rune);

    if (c.isAllLetterUpperCase) {
      buffer.write(c);
    }
  }

  return buffer.toString();
}