Search code examples
flutterdart

What case are numbers and punctuation in Dart's String.toUpperCase and String.toLowerCase methods?


In solving an exercise, I don't fully recognize what Dart's String .toUpperCase() and .toLowerCase() methods do. The documentation is a bit spartan.

The exercise involved being given a String message and recognizing if the message was UPPER CASE. On the surface, it's easy. The body of a method could be simply

return message==message.toUpperCase();

Or maybe something like

message.contains(RegExp(r'[a-z]]') ? return false : return true;

But the String message can have spaces, punctuation, and numbers.

The exercise's community solutions are often more along the lines of

return (message==message.toUpperCase() && message!=message.toLowerCase());

I don't understand what difference this makes, especially when I look at code like this:

void main() {
  String message = ("1, 2, 3!");
  print (message.toUpperCase()); // 1, 2, 3!
  print (message.toLowerCase()); // 1, 2, 3!
  print (message==message.toUpperCase()); // true
  print (message==message.toLowerCase()); // true
}

So, what's happening here? To recognize a message as ALL CAPS, along with spaces, punctuation, and numbers, why would you need to check both .toUpperCase() and .toLowerCase()?


Solution

  • Punctuation and whitespace are neither uppercase nor lowercase. toUpperCase/toLowerCase would not affect them at all.

    The condition

    (message==message.toUpperCase() && message!=message.toLowerCase())
    

    tests that message is already an uppercase string by checking that it is unchanged when transformed to uppercase and that it contains at least one uppercase letter (that is, it does not consist entirely of punctuation or whitespace).