[Chapter 32 of Dart tutorial series] summary of String type methods in Dart. It's enough to read this article

This is part 32 of Dart tutorial series. If you find it useful, you are welcome to follow the column.

The String encoding format in Dart is UTF-16, that is, the code unit sequence of 16 bit Unicode conversion format.

Taking Dart SDK version 2.13.4 as an example, there are 25 string methods in Dart. This blog will talk about 23 of them. Because two of them are too popular, I won't explain them. Next, I will introduce the corresponding methods one by one according to the function of string.

1: String type conversion

toString

The source code is as follows

external String toString();

grammar

All types inherited from Object in Dart support a method, toString(), which can convert the target type to String type.

give an example

int a = 10;
print(a.toString()); // Convert 10 of type int to 10 of type String

List list = [1, 3, 5];
print(list.toString()); // List array type [1, 3, 5] is converted to String type '[1, 3, 5]'

Map map = {"name": "Allen Su", "age": 18};
print(map.toString()); // Map dictionary type converted to "{" name ":" Allen Su "," age ": 18}" of String type

The same is true for other types such as double, num, Set, etc.

2: String lookup

indexOf

The source code is as follows

int indexOf(Pattern pattern, [int start = 0]);

grammar

The specified character is searched from front to back. The return value is of type int. if there are qualified characters, the index of the corresponding character is returned. If it is not found, it returns - 1.

The first parameter is the character to find. Regular expressions are supported. If you see patterns later, you can use regular expressions instead of characters.

The second is an optional parameter. The index from which to start searching (including the index) is 0 by default. Where start cannot be a negative number and is not greater than the string length of the searched character.

give an example

String text = "abcDcbaE";

// 01 find the index of the first occurrence of the character c
print(text.indexOf('c')); // Return 2

// 02 find the index of the first occurrence of character c from the position of index 3
print(text.indexOf('c', 3)); // Return 4

// 03 find the index of the first occurrence of the character p
print(text.indexOf('p')); // //Return - 1

// 04 use regular expressions to find the index when uppercase characters appear for the first time
print(text.indexOf(RegExp('[A-Z]'))); // Return 3

lastIndexOf

The source code is as follows

int lastIndexOf(Pattern pattern, [int? start]);

grammar

Find the specified character from back to front. The return value is of type int. if there are qualified characters, the index of the corresponding character is returned. If not found, it returns - 1. It should be noted in advance that reverse search does not mean that the index is also reversed.

The first parameter is the character to be searched, and the second is an optional parameter. There is no default value at which index to start searching (including the index).

give an example

String text = "abcDcbaE";

// 01 find the index of the first occurrence of character a in reverse order
print(text.lastIndexOf('a')); // Return 6

// 02 find the index of the first occurrence of character a in reverse order from the position of index 2
print(text.lastIndexOf('a', 2)); // Return 0

// 03 find the index of the first occurrence of the character p in reverse order
print(text.lastIndexOf('p')); // Return - 1

// 04 use regular expressions to find the index when uppercase characters appear for the first time in reverse order
print(text.lastIndexOf(RegExp('[A-Z]'))); // Return 7

3: String judgment

contains

The source code is as follows

bool contains(Pattern other, [int startIndex = 0]);

grammar

Judge whether the string contains the specified character. If it exists, return true and if not, return false.

The first parameter is the specified character, and the second parameter is optional, which represents the index position from which to judge. The default is 0, where startIndex cannot be negative and not greater than the length of the string.

give an example

String text = "https://allensu.blog.csdn.net";

// 01 judge whether the string contains the character allensu
print(text.contains('allensu')); // Return true

// 02 judge whether the character CSDN is included in the string
print(text.contains('CSDN')); // Return false

// 03 judge whether the string contains characters from the position of index 8/
print(text.contains('/', 8)); // Return false

startsWith

The source code is as follows

bool startsWith(Pattern pattern, [int index = 0]);

grammar

Judge whether the string starts with the specified character, return true if it is true, and return false if it is not true.

The first parameter is the specified character, and the second parameter is optional, which represents the index position from which to judge. The default is 0, where index cannot be a negative number and is not greater than the length of the string.

give an example

String text = "https://allensu.blog.csdn.net";

// 01 judge whether the string starts with the character https
print(text.startsWith('https')); // Return true

// 02 judge whether the string starts with the character w
print(text.startsWith('w')); // Return false

// 03 judge whether the string starts with the character / / from the index 6 position
print(text.startsWith('//', 6)); //  Return true

endsWith

The source code is as follows

bool endsWith(String other);

grammar

Judge whether the string ends with the specified character, return true if it is true, return false if it is not true, and the parameter other is the specified character.

give an example

String text = "https://allensu.blog.csdn.net";

// 01 determine whether the string ends with the character net
print(text.endsWith('net')); // Return true

// 02 judge whether the string ends with the character w
print(text.endsWith('w')); // Return false

4: String segmentation

substring

The source code is as follows

String substring(int start, [int? end]);

grammar

The first parameter, start, is the index to start splitting the string. When only the start parameter is passed, it means to intercept from the start index to the end of the string.

The second parameter, end, is an optional parameter, which indicates the index of the end split string. The value of end cannot be greater than the length of the string.

The range of string interception is [start, end], that is, including the head and not including the tail.

give an example

String text = "aaabbbccc";

// 01 split string from index 3 position to end
print(text.substring(3)); // Return bbbccc

// 02 split string from index 3 position to index 8 position
print(text.substring(3, 8)); // Return to BBBC

split

The source code is as follows

List<String> split(Pattern pattern);

grammar

Split the string with the specified character. The return type is list < string >, and the split character will not be added to the array.

If the specified split character is not in the string, the entire string is added directly to the array as an element in the new array.

give an example

// 01 split string with character%
String str1 = "a%b%c%d%e%f";
List<String> l1 = str1.split('%');
print(l1); // Returns a list of strings of length 6 [a, b, c, d, e, f]

// 02 split string with spaces
String str2 = "abcdef";
List<String> l2 = str2.split('');
print(l2); // Returns a list of strings of length 6 [a, b, c, d, e, f]

// 03 when the specified character is not in the string
String str3 = "xyz";
List<String> l3 = str3.split('+');
print(l3); // Return to [xyz]

splitMapJoin

The source code is as follows

String splitMapJoin(
  Pattern pattern, {
  String Function(Match)? onMatch,
  String Function(String)? onNonMatch,
});

grammar

This method is quite special. It can complete three things in one sentence. Although I don't usually use it much, I still need to know the purpose of this method.

The first parameter can be a String or a regular RegExp object.

The second parameter is an optional parameter, which means to replace each string that matches the specified split character with a custom returned string.

The third parameter is also an optional parameter, but it is just opposite to the second parameter. It means that each character that does not match the specified split character is replaced with a custom returned string.

give an example

String text = "a,b,c,d";

String val = text.splitMapJoin(
  ',', // Comma as the split character
  onMatch: (Match match) => "y", // Replace the comma in the string with the character y
  onNonMatch: (String nonMatch) => "x", // Replace the string that is not a comma with the character x
);

print(val); // Return xyxyxyx

5: String conversion case

toUpperCase

The source code is as follows

String toUpperCase();

grammar

Convert all lowercase letters in the string to uppercase letters. If they are already uppercase letters or not lowercase letters, such as numbers, return the original characters.

give an example

String text = "abcDe123";
print(text.toUpperCase()); // Return to ABCDE123

toLowerCase

The source code is as follows

String toLowerCase();

grammar

Convert all uppercase letters in the string to lowercase letters. If they are already lowercase letters or not uppercase letters, such as numbers, return the original characters.

give an example

String text = "123AbCdE";
print(text.toLowerCase()); // Return to 123abcde

6: String complement

padLeft

The source code is as follows

String padLeft(int width, [String padding = ' ']);

grammar

The left complement of the string. After the width is specified, if there are remaining bits, it will be replaced with the specified character. If the specified width is less than the string length, the original string is returned.

The first parameter width is not the total length of the supplemented string. You can use width to subtract the length of the original string. The result shows how many supplemented characters will be added to the left of the string (see examples 01, 02 and 03 below)

The second parameter padding is an optional parameter, which indicates the characters to be supplemented. If it is not specified, a space is filled in by default.

give an example

String text = "5";

// 01 to the left of the specified string, add (4-text.length=3) spaces to the original string
print(text.padLeft(4)); // Return to "5". Note that there are three spaces to the left of character 5

// 02 add (4-text.length=3) characters 2 to the original string to the left of the specified string
print(text.padLeft(4, '2')); // Return to 2225

// 03 add (4-text.length=3) characters 22 to the original string to the left of the specified string
print(text.padLeft(4, '22')); // Return 2222225

// 04 when the minutes of time are single digits, you can fill 0 on the left to achieve the effect of double digits display
print(text.padLeft(2, "0")); // Return to 05

// 05 if the width is less than the length of the string, the original string is returned
print(text.padLeft(1, '2')); // Return 5

padRight

The source code is as follows

String padRight(int width, [String padding = ' ']);

grammar

The right complement of the string. After the width is specified, if there are remaining bits, the specified character will be used for replacement. If the specified width is less than the string length, the original string is returned.

The first parameter width is not the total length of the supplemented string. You can use width to subtract the length of the original string. The result shows how many supplemented characters will be added to the right of the string (see examples 01, 02 and 03 below)

The second parameter padding is an optional parameter, which indicates the characters to be supplemented. If it is not specified, a space is filled in by default.

give an example

String text = "5";

// 01 to the right of the specified string, add (4-text.length=3) spaces to the original string
print(text.padRight(4)); // Return to "5". Note that there are three spaces to the right of character 5

// 02 add (4-text.length=3) characters 2 to the original string to the right of the specified string
print(text.padRight(4, '2')); // Return to 5222

// 03 add (4-text.length=3) characters 22 to the original string to the right of the specified string
print(text.padRight(4, '22')); // Return to 5222222

// 04 if the width is less than the length of the string, the original string is returned
print(text.padRight(1, '2')); // Return 5

7: Remove spaces from string

trim

The source code is as follows

String trim();

grammar

Remove the left and right spaces in the string. Note that not all spaces in the string are removed. If there are no spaces on either side, the original string is returned.

give an example

String text = "   a b c "; // String of length 9
print(text.trim()); // Returns the string "a b c" of length 5

trimLeft

The source code is as follows

String trimLeft();

grammar

Remove the space on the left of the string. If there is no space on the left, the original string is returned.

give an example

String text = "   a b c "; // String of length 9
print(text.trimLeft()); // Returns the string "a b c" of length 6, and the space to the right of character c is reserved

trimRight

The source code is as follows

String trimRight();

grammar

Remove the space on the right in the string. If there is no space on the right, the original string is returned.

give an example

String text = "   a b c "; // String of length 9
print(text.trimRight()); // Returns the string "a b c" of length 8, and the three spaces to the left of character a are reserved

8: String substitution

replaceAll

The source code is as follows

String replaceAll(Pattern from, String replace);

grammar

Replace all qualified characters in the string. If there is no matching string, the original string is returned.

The first parameter from represents the character replaced in the string, and the second parameter replace represents why the character is replaced.

give an example

String text = "abcdabcd";
print(text.replaceAll("ab", "xy")); // Return xycdxycd

replaceFirst

The source code is as follows

String replaceFirst(Pattern from, String to, [int startIndex = 0]);

grammar

Replace only the first eligible character.

The first parameter from indicates the character replaced in the string, the second parameter to indicates why the character is replaced, and the third parameter is an optional parameter, indicating the index position from which to replace, which is 0 by default.

give an example

String text = "abcdabcd";

// 01 replace only the first qualified character
print(text.replaceFirst("ab", "xy")); // Return xycdabcd

// 02 replace the first qualified character from the position after index 1
print(text.replaceFirst("ab", "xy", 1)); // Return abcdxycd

replaceRange

The source code is as follows

String replaceRange(int start, int? end, String replacement);

grammar

Replace the characters within the specified range. The valid value range is 0 < = start < = end < = string. length.

The first parameter start indicates the index position from which to start the replacement, including the index.

The second parameter end indicates the index position from which the replacement ends, excluding the index. Because end is an nullable parameter, when end is null, it indicates to the end of the string.

The third parameter, replacement, indicates why to replace the character.

give an example

String text = "abcdabcd";

// 01 from index 0 to index 3 (but excluding the index), the middle character is replaced with m
print(text.replaceRange(0, 3, "m")); // Return mdabcd

// 02 from the index 0 position to the end, the middle character is replaced with m
print(text.replaceRange(0, null, "m")); // Return m

replaceAllMapped

The source code is as follows

String replaceAllMapped(Pattern from, String Function(Match match) replace);

grammar

Replace all eligible characters. Replace the specified character with the return value of the method. If there is no matching character, the original string is returned.

The first parameter from represents the replaced character in the string,

The second parameter, replace, indicates that if there are matching characters, the specified characters will be used as the return value to replace the qualified characters in the string. The final effect is actually the same as the method replaceAll.

give an example

String text = "abcdabcd";

// Replace ab in the string with xy
String str = text.replaceAllMapped("ab", (Match match) => "xy");
print(str); // Return xycdxycd

replaceFirstMapped

The source code is as follows

String replaceFirstMapped(Pattern from, String replace(Match match), [int startIndex = 0]);

grammar

Replace only the first eligible character. Replace the specified character with the return value of the method. If there is no matching character, the original string is returned.

The first parameter from represents the replaced character in the string,

The second parameter replace means that if there is a matching character, the specified character is used as the return value to replace the first qualified character in the string. The final effect is actually the same as the method replaceFirst.

The third parameter, startIndex, is an optional parameter, indicating the index position from which to replace. It defaults to 0 and cannot be greater than the length of the string.

give an example

String text = "abcdabcd";

// 01 replace the first qualified ab in the string with xy
String str1 = text.replaceFirstMapped("ab", (Match match) => "xy");
print(str1); // Return xycdabcd

// 02 replace the first qualified ab in the string with xy from the position of index 1
String str2 = text.replaceFirstMapped("ab", (Match match) => "xy", 1);
print(str2); // Return abcdxycd

9: String sequential comparison

compareTo

The source code is as follows

int compareTo(String other);

grammar

Compare the position of characters in ASCII code.

If the current character is after the compared character, it returns 1, and if the positions are equal, it returns 0. If the current character is before the compared character, it returns - 1.

In ASCII code, 48 ~ 57 are ten Arabic numerals from 0 to 9, 65 ~ 90 are 26 uppercase English letters, and 97 ~ 122 are 26 lowercase English letters.

give an example

String text = "b";

print(text.compareTo('a')); // b> A, return 1
print(text.compareTo('b')); // b=b, return 0
print(text.compareTo('c')); // B < C, return - 1
print(text.compareTo('7')); // Letters after numbers return 1
print(text.compareTo('B')); // Lowercase letters after uppercase letters return 1

10: Gets the Unicode encoding of the string

codeUnitAt

The source code is as follows

int codeUnitAt(int index);

grammar

Returns the Unicode decimal encoding of the character at the specified index

give an example

String text = "Allen Su";

print(text.codeUnitAt(0)); // The character at index 0 is A, and A's Unicode decimal encoding is 108
print(text.codeUnitAt(5)); // The characters at index 5 are spaces, and the Unicode decimal encoding of spaces is 32

There are also two methods, matchAsPrefix and allMatches, which are too popular. I won't explain them here.

If you need to know Property of String type in Dart , you can click the link to jump.

It's not easy to finish this blog. Fortunately, I insisted on finishing it at one breath.

Has your problem been solved? Welcome to leave a message in the comment area.

Give someone roses with lingering fragrance in your hand. If you think the article is good, I hope you can give me a key three times. Thank you.

Conclusion

Technology is accumulated bit by bit, and the great God can not be achieved in a day. Standing still is a step back, so make progress a little every day.

Finally, a motto is attached: "learning is like hunger, humility is like stupidity". I hope we can encourage each other.

Keywords: dart

Added by kuliksco on Tue, 12 Oct 2021 07:19:14 +0300