Exploring String methods in Dart
In my last article, I talked about various methods List
provides that we can use to manipulate and retrieve data per our need.
In today’s article, we will take a look at various methods associated with String
a datatype and how they can be utilized, with practical usage of each.
Let’s get started.
String
is one of the most commonly used data type in programming languages and Dart is no exception.
String
is nothing but a plain text that can contain one or more characters including a combination of letters and numbers (alpha-numeric) or special characters. This kind of data representation is considered to be String
as long as it is included in single or double-quotes. For instance, the below variables are of String
datatype:
firstStr = 'Password@123';
secondStr = "Audi A8";
Extracting correct data from source
The methods String
the class provides, helps us to apply filters on the incoming data and retrieve only the ones that are expected to be displayed on the screen. But only using the methods directly to manipulate and retrieve data is not enough, we also need to check for following conditions based on the requirement for a particular element, while processing the string data:
- The first and last names should not contain whitespaces and numbers.
- An address should not contain special chars.
- The phone number should not contain text.
We can validate the above conditions using Regular Expression
. RegEx or RegExp comes very handy when we have to validate above-listed conditions by searching for one or more matches of a pattern. Dart provides RegExp
a class which is used to match strings or part of strings.
Most of the String method calls in Dart take pattern as an input parameter which is nothing but a condition we need to validate on the input string. Here we will make use of RegExp class to check for specific conditions because we need to take into consideration all cases (numbers, special chars, uppercase, space and so on) to retrieve the string per our needs and will make sure the string we are rendering on screen is in the expected form.
In the following methods, we will use a basic regex
as applicable, to match a specific pattern.
substring():
When we want to perform an action or retrieve part of a given string based on a condition, we use this method. It takes an index as input and returns the rest of the string from a position of the index provided. It also takes an optional endIndex which is exclusive of the resulting string.
- Example: let’s say we want to capitalize the first letter of a string, then we can use
substring
method for it as below:
String str = "welcome";
print(str[0].toUpperCase() + str.substring(1)); // Welcome
Here we used toUpperCase
method to capitalize letter at index 0 and since we need to keep rest of the string as-is, we made use of substring()
starting from index 1, so that it’ll take the string starting from e till the length of it (elcome)
.
startsWith():
This method returns a bool when the string matches the pattern. Optionally, we can provide an index from where the pattern matching should start.
- Example: let’s say we want to check if the given string starts with a number.
String strWithNum = "5welcome";
print(strWithNum[0].startsWith(RegExp(r'[0-9]'))); // trueString strNoNum = "welcome";
print(strNoNum[0].startsWith(RegExp(r'[0-9]'))); // false
Here, since we want to check from the starting position of the string, we provided index 0 and then used regex
an object to match the pattern. r’[0–9]’
checks for number from 0 to 9 as a single character.
split():
This method is used to split given string into substring which further can be used to retrieve or perform an action on substrings.
- Example: let’s say we want to convert a given string to a list, we use split() method as:
String strList = "Welcome To Dart World";
print(strList.split(' ')); // [Welcome, To, Dart, World]
Here, depending on what we pass as delimiter
, it returns list of all substrings. If we want to return list of all letters, then we use split() as:
String strList = "Welcome To Dart World";
print(strList.split('')); // [W, e, l, c, o, m, e, , T, o, , D, a, r, t, , W, o, r, l, d]
Further, this method can be combined with other methods to retrieve the data per our need.
- Example 2: let’s say we have a string that has duplicate / repeated words and we want to remove them before rendering it on screen.
String dupStr = "This string has has a typo";
We’ll first use split()
with a space delimiter
to separate all words from given string and then apply toSet()
that returns single instance (occurence) of elements if it finds same elements. So, the implementation looks like:
String dupStr = "This string has has a typo";
print(dupStr.split(' ').toSet().join(' ')); // This string has a typo
Here, we also use join()
with space delimiter
to properly return the result in string format.
replaceAll():
This method is used to replace part of given string that matches the pattern with new string. It takes pattern to check the condition and new string to be replaced by the pattern.
- Example: let’s say we want to mask email id and show only a part of it like (d*******@test.com), then using
replaceAll()
method will look like:
String email = "johndoe@email.com";
print(email.replaceAll(RegExp(r'(?<=.{1}).(?=.*@)'), '*')); // j******@email.com
- Example 2: if we want to remove all numbers from a given string, we can do that using replaceAll() as:
String strWithDig = "abc123defg456";
print(strWithDig.replaceAll(RegExp(r'[0-9]'), '')); // abcdefg
replaceFirst():
Similar to replaceAll()
, if we just want to replace first few characters from a given string, we use this method.
- Example: let’s say we want to replace numbers from given string with letters, we use
replaceFirst()
as:
String replace = "123def";
final repReg = RegExp(r'\d{3}');
print(replace.replaceFirst(repReg, 'abc')); // abcdef
allMatches():
This method matches the pattern against the given string repeatedly by taking the string to be matched as first parameter and an optional start index to begin pattern matching.
- Example: let’s say we want to retrieve and display only numerals from a given string, we’ll use this method as:
String strNum = "This string has numbers 123456 and 78910";
final iReg = RegExp(r'(\d+)');
print(iReg.allMatches(strNum).map((m) => m.group(0)).join(' ')); // 123456 78910
Here, since we want to search for numbers in the given string, we first define corresponding regex
for it and assign it to a variable that will perform match on given string. Hence, we used iReg.allMatches(strNum)
which will return instances of matching pattern. Next, we want to extract the actual numbers so we use map
that will return all mapped elements by using group
method call and finally we use join()
with space delimiter to display the numbers extracted.
compareTo():
This method is used to compare one input with other and returns an integer.
- Example: let’s say we want to compare length of two input strings, we’ll use this method as:
String first = "This is first string";
String second = "This is another string";
print(first.length.compareTo(second.length)); // -1// -1 indicates first input is less than second
// 0 indicates both inputs are equal
// 1 indicates second input is greater than first
splitMapJoin():
This method splits the given string, converts its parts per requirement, and combines them into a new string. It takes pattern
which could be a string or regex object, onMatch
that converts each match to a string and onNonMatch
which converts each non-matching part to string.
- Example: let’s say we want to highlight first capital letter of each word by enclosing each in square bracket from given string, we’ll use this method as :
String resStr = 'This Is The Biggest Revolution In This Decade';
print(resStr.splitMapJoin(
RegExp(r'[A-Z]'),
onMatch: (m) => '[${m.group(0)}]',
onNonMatch: (n) => '${n.substring(0)}'));// [T]his [I]s [T]he [B]iggest [R]evolution [I]n [T]his [D]ecade
the regex
pattern is given since we need to identify and highlight capital letters from given string. Enclose the letter with []
upon pattern matching and for rest of the letters of each word, return the string as is, using substring()
.
There are more methods that I didn’t cover today, but here’s a run down on some of them:
- trim(): returns a new string without any
whitespace characters
at the beginning or end. There are two variants of this methods trimLeft() and trimRight(). - padLeft(): returns a right-justified string with given minimum
width
. - padRight(): returns a left-justified string with given minimum
width
. - replaceRange(): returns new string which is substring from start to end index with string to be replaced.
- isEmpty(): returns true if string is empty.
- isNonEmpty(): returns true if string is not empty.
That’s all I have in this article. We saw how String
methods can be used effectively using regex
to extract data per our need that can be very helpful in how we render String
data on screen.
Thanks for reading through and I hope you liked what you read here. Feel free to comment below your thoughts or any comment /suggestions/feedback on this article or you may also connect with me on Twitter, LinkedIn and Github.
My other articles on Flutter and Dart are: