Dart程式設計 - 字串



字串資料型別表示一系列字元。Dart字串是UTF-16程式碼單元的序列。

Dart中的字串值可以使用單引號、雙引號或三引號表示。單行字串使用單引號或雙引號表示。三引號用於表示多行字串。

在Dart中表示字串值的語法如下所示:

語法

String  variable_name = 'value'  

OR  

String  variable_name = ''value''  

OR  

String  variable_name = '''line1 
line2'''  

OR  

String  variable_name= ''''''line1 
line2''''''

以下示例演示了在Dart中使用字串資料型別的用法。

void main() { 
   String str1 = 'this is a single line string'; 
   String str2 = "this is a single line string"; 
   String str3 = '''this is a multiline line string'''; 
   String str4 = """this is a multiline line string"""; 
   
   print(str1);
   print(str2); 
   print(str3); 
   print(str4); 
}

它將產生以下輸出

this is a single line string 
this is a single line string 
this is a multiline line string 
this is a multiline line string 

字串是不可變的。但是,字串可以進行各種操作,所得字串可以作為新值儲存。

字串插值

透過將值附加到靜態字串來建立新字串的過程稱為連線插值。換句話說,就是將一個字串新增到另一個字串的過程。

加號運算子(+)是常用的連線/插值字串的方法。

示例1

void main() { 
   String str1 = "hello"; 
   String str2 = "world"; 
   String res = str1+str2; 
   
   print("The concatenated string : ${res}"); 
}

它將產生以下輸出

The concatenated string : Helloworld

示例2

您可以使用"${}"在字串中插值Dart表示式的值。以下示例說明了這一點。

void main() { 
   int n=1+1; 
   
   String str1 = "The sum of 1 and 1 is ${n}"; 
   print(str1); 
   
   String str2 = "The sum of 2 and 2 is ${2+2}"; 
   print(str2); 
}

它將產生以下輸出

The sum of 1 and 1 is 2 
The sum of 2 and 2 is 4

字串屬性

下表中列出的屬性都是隻讀的。

序號 屬性及描述
1 codeUnits

返回此字串的UTF-16程式碼單元的不可修改列表。

2 isEmpty

如果此字串為空,則返回true。

3 length

返回字串的長度,包括空格、製表符和換行符。

操作字串的方法

dart:core庫中的String類還提供了一些操作字串的方法。其中一些方法如下所示:

序號 方法及描述
1 toLowerCase()

將此字串中的所有字元轉換為小寫。

2 toUpperCase()

將此字串中的所有字元轉換為大寫。

3 trim()

返回不包含任何前導和尾隨空格的字串。

4 compareTo()

將此物件與另一個物件進行比較。

5 replaceAll()

將與指定模式匹配的所有子字串替換為給定值。

6 split()

在指定分隔符的匹配處分割字串,並返回子字串列表。

7 substring()

返回此字串的子字串,該子字串從startIndex(包含)擴充套件到endIndex(不包含)。

8 toString()

返回此物件的字串表示形式。

9 codeUnitAt()

返回給定索引處的16位UTF-16程式碼單元。

廣告