Recent site activity

2. Learn‎ > ‎d. Variables‎ > ‎

a. String

A string is a sequence of Unicode characters 
  • Strings are immutable objects and cannot be changed
  • Create strings with single or double quotes
  • Interpolate strings with ${expression} or $variable
  • Concatenate strings over multiple lines
  • Create multiline triple quote strings
  • + will not concatenate, use String interoperation
References
Strings Examples 

String with out Type Annotation
var s = 'single quotes';

Single quotes
String s = 'single quotes';

Double quotes
String s = "double quotes";

Single quote escape \' 
String s = 'I\'ve got single quotes';

Singe quote encapsulation  "'" or "''"
String s = "I've got double and single quotes";


String Interpolate

String $variable interpolation
String color = "grey";
String s = "I have a $color house.";

String ${expression} interpolation
String s = "I have ${2+3} chickens.";


Multiline Strings

Multiline consecutive string concatenate
String s = "consecutive multiline string" ' concatenation'
           
" makes strings fun.";

Multiline triple quote 
String s = """
line 1
line 2
"""
;

Multiline single quote. String concatenate over multilines with consecutively quotes. 
var s = 'line 1'
       
'line 2'
       
'line 3';


Raw Strings

Raw string prefix @
String s = @'In a raw string, even \n is ignored.';


Strings and Methods

Equals
String left = 'hand';
String right = "hand";
print(left == right); // is true

String Methods - String API
String s = 'Cuthbert Musgrave Girdlestone, III';
s
.startsWith('Cuthbert');            // is true
s
.endsWith('III');                   // is true
s
.contains(new RegExp('Musgrave'));  // is true

String Buffer
StringBuffer sb = new StringBuffer();
sb
.add("A");
sb
.addAll(["B", "C", "D", "E"]);
sb
.add("F").add("G");
String alphabet = sb.toString();
print(alphabet);
sb
.clear();

String replace, changing a multiline to single line by replacing the new line > '\n' - Try Code
var multiline = "line1\nline2\nline3";
var singleline = multiline.replaceAll("\n", " ");
print(singleline);



Comments