Groovy - 字串



Groovy 中的字串字面量是用引號括起來的字串文字構造的。

Groovy 提供多種方法來表示字串字面量。Groovy 中的字串可以用單引號 (’)、雙引號 (“) 或三引號 (“””) 括起來。此外,用三引號括起來的 Groovy 字串可以跨越多行。

以下是 Groovy 中字串用法的示例:

class Example { 
   static void main(String[] args) { 
      String a = 'Hello Single'; 
      String b = "Hello Double"; 
      String c = "'Hello Triple" + "Multiple lines'";
		
      println(a); 
      println(b); 
      println(c); 
   } 
}

執行以上程式,我們將得到以下結果:

Hello Single 
Hello Double 
'Hello TripleMultiple lines'

字串索引

Groovy 中的字串是字元的有序序列。字串中的單個字元可以透過其位置訪問。這由索引位置給出。

字串索引從零開始,到字串長度減一結束。Groovy 也允許使用負索引從字串末尾反向計數。

以下是 Groovy 中字串索引用法的示例:

class Example { 
   static void main(String[] args) { 
      String sample = "Hello world"; 
      println(sample[4]); // Print the 5 character in the string
		
      //Print the 1st character in the string starting from the back 
      println(sample[-1]); 
      println(sample[1..2]);//Prints a string starting from Index 1 to 2 
      println(sample[4..2]);//Prints a string starting from Index 4 back to 2 
      
   } 
}

執行以上程式,我們將得到以下結果:

o 
d 
el 
oll 

基本字串操作

首先讓我們學習 Groovy 中的基本字串操作。它們如下所示。

序號 字串操作和描述
1 兩個字串的連線

字串連線可以使用簡單的 ‘+’ 運算子完成。

2 字串重複

字串重複可以使用簡單的 ‘*’ 運算子完成。

3 字串長度

字串長度由字串的 length() 方法確定。

字串方法

以下是 String 類支援的方法列表。

序號 方法和描述
1 center()

返回一個長度為 numberOfChars 的新字串,該字串由接收者組成,並在左側和右側用空格字元填充。

2 compareToIgnoreCase()

忽略大小寫差異地按字典順序比較兩個字串。

3 concat()

將指定的字串連線到此字串的末尾。

4 eachMatch()

處理給定字串中匹配的每個正則表示式組(參見下一節)子字串。

5 endsWith()

測試此字串是否以指定的結尾字尾結束。

6 equalsIgnoreCase()

比較此字串與另一個字串,忽略大小寫。

7 getAt()

它返回索引位置處的字串值

8 indexOf()

返回此字串中指定子字串第一次出現的索引。

9 matches()

它輸出字串是否與給定的正則表示式匹配。

10 minus()

刪除字串的值部分。

11 next()

此方法由 String 類的 ++ 運算子呼叫。它遞增給定字串中的最後一個字元。

12 padLeft()

在字串左側新增空格進行填充。

13 padRight()

在字串右側新增空格進行填充。

14 plus()

追加字串

15 previous()

此方法由 CharSequence 的 -- 運算子呼叫。

16 replaceAll()

用對該文字的閉包的結果替換捕獲組的所有出現。

17 reverse()

建立一個新的字串,它是此字串的反轉。

18 split()

根據給定正則表示式的匹配拆分此字串。

19 subString()

返回一個新的字串,它是此字串的子字串。

20 toUpperCase()

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

21 toLowerCase()

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

廣告
© . All rights reserved.