Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if the first letter of string is in uppercase in Dart

Tags:

flutter

dart

I want to check if the first letter of string is in uppercase in Dart language. How can I implement it? Thanks in advance.

like image 907
valerybodak Avatar asked May 15 '19 18:05

valerybodak


2 Answers

The simplest way I can think of is to compare the first letter of the string with the uppercase equivalent of it. Something like:

bool isUpperCase(String string) {
    if (string == null) {
      return false;
    }
    if (string.isEmpty) {
      return false;
    }
    if (string.trimLeft().isEmpty) {
      return false;
    }
    String firstLetter = string.trimLeft().substring(0, 1);
    if (double.tryParse(firstLetter) != null) {
      return false;
    }
    return firstLetter.toUpperCase() == string.substring(0, 1);      
}

Updated the answer to take in consideration digits.

Also @Saed Nabil is right, this solution will return true if the string starts with any character that is not a letter (except for digits).

like image 76
danypata Avatar answered Nov 04 '22 16:11

danypata


You can use the validators library if you are not already using it. Then use this method

isUppercase(String str) → bool check if the string str is uppercase

Don't forget to import the dependency, see documentation, to the pubspec.yaml and to your code import 'package:validators/validators.dart';.

Example code:

if(isUppercase(value[0])){
  ... do some magic
}

You should check that the value is not empty and not null first for safety. Like this:

if(value != null && value.isNotEmpty && isUppercase(value[0])){
  ... do amazing things
}
like image 2
Haroun Hajem Avatar answered Nov 04 '22 15:11

Haroun Hajem