“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: 2021 Last Gwen Challenge”
preface
As the most common type used in development, string follows certain specifications, which can effectively improve the readability of code. The following recommended practices for using strings in Dart.
String conjunction
If you have two literal strings (not variables, but strings in quotes), you don’t need to use + to concatenate them. Just put them next to each other, which is good for creating long strings that can’t fit on a single line.
///recommended
String f = 'aaa''bbb' // Applies only to constants but not to variables
///The + sign is not recommended
String f = 'aaa' + 'bbb'
Copy the code
String definition
Use three single quotes or three double quotes to create a multi-line string with built-in formatting such as newline and indentation
String f = ''' my name is rex nice to meet you! ' ' '
Copy the code
Common definition, using single or double quotation marks
String a = 'aaa';
String b = "bbb";
Copy the code
Special characters such as the raw string escape character created with r are printed instead of being automatically escaped
String f = r'Hello \n World';
Copy the code
Use interpolation to combine strings and values
Avoid using + to associate literal strings with variable values. Build the connection using the $,${} identifier.
void setName(Person person){
String f = 'my name ${person.name}'
}
void setName(String name){
String e = 'my name is $name'
}
Copy the code
Change case
Business comparisons often ignore case and only compare content
String f = "aaaBBBccc";
// Uppercase to lowercase
f.toLowerCase();
// Change lowercase to uppercase
f.toUpperCase();
Copy the code
Remove the blank space
Removing whitespace is also a common use in development
String f = " aaabbb "
// Remove the left and right Spaces
f.trim();
// remove the left space
f.trimLeft();
// remove the space on the right
f.trimRight();
Copy the code
Complete the length, and replace the remaining bits with the specified string
String f = "111";
// The left side defaults to "complete"
f.padLeft(6); / / "111"
// Use "c" to complete the left 3 bits
f.padRight(6."c"); //"111ccc"
// The remaining 3 bits each specify that the total length is not 6 when replaced with "dd"
f.padRight(6."cc"); //"111cccccc"
If the specified length is less than the length of the original string, the original string is returned
f.padLeft(2); / / "111"
Copy the code