DEV Community

Cover image for The Beauty of Dart String Methods
Motabar Javaid
Motabar Javaid

Posted on • Updated on

The Beauty of Dart String Methods

Dart is a Google's client-optimized Object Oriented Programming Language which is used to build User Interfaces in conjunction with Flutter - A Cross Platform Development Toolkit.

Dart is a statically typed language that offers features like Sound Null Safety , Spread operators, Collection if's for its Collection class and the powerful Dart VM that enables it to have its renowned Hot Reload functionality.
Like any other Programming Languages, Dart offers String as types. It can be represented with either a single, double or triple quotes. 

What makes Dart Strings special is the Methods that are available for the String Types. Here are some which comes in very handy when dealing with String literals.



void main() {

  String thisIsAString = 'Hello World'; //Explicitly typed variable
  var thisIsAlsoAString = "Hello World Again";  // Implicitly typed variable
  String tripleQuotedString = """ This is a triple-quoted String """;

  print(thisIsAString);  //Prints Hello World onto the console

}

Enter fullscreen mode Exit fullscreen mode

endsWith():

The endsWith Method takes a String as an argument and returns true if the String on which it is called ends at the given parameter.Its worth mentioning, the endsWith Method is case sensitive. Let's see that in practice:



void main(){
  String name = 'I am Motabar';
  String notSoSophisticatedString = 'i Am mOTAbAR';

  print(name.endsWith('r')); // Returns true as the parameter 'r' is same as 'r' in variable name's last character

  print(notSoSophisticatedString.endsWith('r')); //Returns false as parameter 'r' does not match with variable's last character 'R'


}

Enter fullscreen mode Exit fullscreen mode

trim():

Have you ever felt lazy while removing trailing or leading white spaces from large Strings? Dart's trim Method got you covered. When called, it returns a new String with no whitespaces. Here's the code:



void main() {

  String aVeryLongString = "      This is a very long string with leading as well as trailing white spaces    "
  String trimmedString = aVeryLongString.trim();

//   The trimmedString Variable has now removed all the leading and trailing white spaces.

  print(trimmedString);  //Prints "This is a very long string with leading as well as trailing white spaces"

}


Enter fullscreen mode Exit fullscreen mode

replaceAll():

The replaceAll function on Strings takes two string parameters: First one is the substring that is to be replaced and the second one is the one with which it is to be replaced with. The function replaces the string with the substring at all the instances within that String. Confused? Let's make it easier by looking at an example:



void main() {

  String justAnotherString = 'And then she said: "Valar Morghulis" ';

  //modifiedString Variable now contains the string with original String's "Morghulis" replaced by "Dohaeris".
  String modifiedString = justAnotherString.replaceAll('Morghulis', 'Dohaeris');

  print(modifiedString);  //'Prints "And then she said: Valar Dohaeris '


}

Enter fullscreen mode Exit fullscreen mode

compareTo():

We'll all been there at some points where we want to compare two Strings but just can't do it with the '==' operator. Why can't we do that, putting it in simpler words is because the equality operator doesn't compare the exact literals but the Object references. So what's the solution? Here comes compareTo() method to the rescue. The Method takes in two parameters: The first one being the one you want to compare and the second one, you guessed it right, the one to which we want to compare our String. The function has three return values based on the result:

  • 0 : When the two Strings match.
  • 1: When the first string is greater than the second (based on ASCII values).
  • -1: When the first string is smaller than the second string. Let's see its functionality by looking at an example:


void main() {

  String firstCharacter = 'A';
  String secondCharacter = 'B';
  String thirdCharacter = 'A';


  print(firstCharacter.compareTo(secondCharacter)); //Returns -1 as the firstCharacter's ASCII value(65) is smaller than secondCharacter (66)

  print(firstCharacter.compareTo(thirdCharacter)); //Returns 0 as both the String literals are equal

  print(secondCharacter.compareTo(firstCharacter)); //Returns 1 as ASCII value of 'B' is indeed greater than 'A'

}

Enter fullscreen mode Exit fullscreen mode

toLowerCase() & toUpperCase():

The toLowerCase() and toUpperCase() methods are self explanatory. The former convert the string literal into Lower-case while the latter does the opposite and converted the string into Upper-case characters. Here's an example containing both:



void main() {

  String firstName = 'MotaBar';
  String lastName = 'javaid';

 print(firstName.toLowerCase());  // print 'motabar' on the console

  print(lastName.toUpperCase()); //prints 'JAVAID' on the console


}

Enter fullscreen mode Exit fullscreen mode

split():

The split() method splits up the string by taking a parameter as a delimeter and returns back the result in the form of List of splitted substrings. Let's look at a code example for it:



void main() {

 String unSplittedString = "This String is to be splitted";


 //prints the list of substrings that gets splitted based on the delimeter which is a blank space.

  print(unSplittedString.split(' ')); // returns [This, String, is, to, be, splitted]

 String oneMoreString = "He ate an apple. And then went on to take a nap";

 //prints the list of two Substrings with a period being the delimeter.

  print(oneMoreString.split('.')); // returns [He ate an apple,  And then went on to take a nap]

}

Enter fullscreen mode Exit fullscreen mode

substring():

The substring() method on dart String literals provides us with the functionality of retreiving a substring by its position. It takes in two parameters: The starting index (inclusive )and the ending index (exclusive). The second parameter is optional. The subString() method in code works as follows:



void main() {

 String unSplittedString = "This String is to be splitted";

  //Start at 0 index(T) and end at, not including index 4(a whitespace).

  print(unSplittedString.substring(0,4));  // prints 'This'

  //We can also only define a starting index and not the ending index, 
  // in such cases, the substring will be as long as the original string   

  print(unSplittedString.substring(5,)); // prints 'String is to be splitted'

}

Enter fullscreen mode Exit fullscreen mode

toString():

Last but not the least, probably the one any developer would be mostly using is the toString() method. The sole purpose of this method is to return the string representaion of the object on which it is called. Let's see it in action:



void main() {

 int anInteger = 45;
 double aDouble = 65.0;
 bool aBoolean = false;

 // Converts the int variable anInteger into type String   
  print("This integer is now a String: ${anInteger}");

  // Converts the double variable aDouble into type String   
  print("This double is now a String literal: ${aDouble}");

   // Converts the bool variable aBoolean into type String   
  print("The boolean's value is not a value but a string and that is : ${aBoolean}");



}

Enter fullscreen mode Exit fullscreen mode

That's all for now Folks! Thanks for reading this article ❤️
Feel free to post any queries or corrections you think are required ✔
Do leave a feedback so I can improve my content. Thankyou! 😃

Discussion (2)

Collapse
vladsolokha profile image
Vlad Solokha

Motabar, I enjoyed reading through your article on string methods. Thanks for the list. I am thinking about beginning creating iOS apps in Flutter as opposed to xcode. Do you have any recommendations for me as I begin the journey. I'm an intermediate programmer with React, Angular, Python, and JavaScript experience.

Collapse
iizmotabar profile image
Motabar Javaid Author

Glad to know you enjoyed the article, Vlad. Since you've programming experience, I would recommend you to get started with the documentation. First of the Dart language and then Flutter docs and the codelabs. That way you'll find yourself comfortable with it in no time!