OneBite.Dev - Coding blog in a bite size

Capitalize A String In Dart

Code snippet for how to Capitalize A String In Dart with sample and detail explanation

Manipulating strings is both vital and fundamental in any programming language. Understanding how to capitalize a string in Dart is one performance of text manipulation that we will walk through in this simple tutorial.

Code snippet for Capitalizing a String in Dart

Here is a simple code snippet that could be used to capitalize a string in Dart.

String capitalize(String str) {
  if (str == null) {
    throw ArgumentError("string: $str");
  }

  if (str.isEmpty) {
    return str;
  }

  return str[0].toUpperCase() + str.substring(1);
}

void main() {
  print(capitalize('capitalize this string in dart'));
}

Code Explanation for Capitalizing a String in Dart

We’ll walk through how the given code works, step-by-step.

  1. We begin by defining a function capitalize that accepts a String str as an argument.

  2. On the next line, we include an important validation check to make sure that the provided string is not null. If it is null, an ArgumentError is thrown with a corresponding message.

  3. Next, we check to see if the provided string is empty. If so, the code will just return the initial empty string.

  4. If the string passes the two checks: one, it’s not empty and two, it’s not null, the function will move on to the next step.

  5. The next line is where the actual capitalization happens. The code takes the first letter of the string, denoted by str[0], and uses the toUpperCase() function to capitalize it.

  6. The rest of the string (i.e., every character after the first one), is kept the same as in the original string. This is accomplished by the substring(1) function.

  7. Finally, the last two lines set the main() function to print the capitalized version of the string ‘capitalize this string in dart’.

Thus, this simple yet crucial Dart function allows you to easily capitalize the first letter of any string.

dart