程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Groovy >> 在Groovy中使用字符串

在Groovy中使用字符串

編輯:Groovy

Groovy支持兩種類型字符串:一般的Java字符串,它是java.lang.String的實例;和GStrings,它是 groovy.lang.GString的實例,並且允許文本中包含占位符。GStrings並不是String的子類,因為String 類是最終類(final class)不能被繼承。然而,GString與一般的字符串一樣,因為Groovy能將 GStrings轉型為Java strings。

GString 適用於編寫模板代碼(templating),因為您必須動態構建字符串(GStrings are useful in templating situations where you have to build your string dynamicly)。以下的清單給出了 一個例子。

使用GStrings:

firstWord = 'Hello'
secondWord = 'dlroW'
println  "$firstWord  ${secondWord.reverse()}"

結果如下:

Hello World

GStrings不同於Java strings在於它們允許以${..}的語法嵌入變量。如果一個字符串由雙引號或三 重引號括起來,並且包含一個非轉義符(unescaped)$,它必定是groovy.lang.GString的一個實例;否 則,就是java.lang.String的一個實例。

${..}裡可以包含任意有效的Groovy表達式,包括方法調用或變量名。只有調用GString的toString方 法時(例如,把結果輸出到控制台),${..}表達式才被求值。

Groovy支持的另一種字符串便是java.lang.String。然而,GDK還是動態注入許多幫助方法,使其易 於應用。

以下的例子展示了在Groovy中聲明一個字符串的不同方式:

s1 = "Hello \"World\" " //Escape double quotes,轉義雙引號
s2 = 'Hello "World" '
assert s1 == s2
s3 = 'Hello \'World\' ' //Escape single quotes,轉義單引號
s4 = "Hello 'World' "
assert s3 == s4
assert new String('Hello World') == "Hello World"
def s = ['h','e','l','l','o'] as char[]
assert new String(s) == 'hello'
assert new String(s,0,4) == 'hell'
s.eachWithIndex{ch,index -> assert ch == s[index]}
assert 'hello'.toCharArray() == ['h','e','l','l','o']

常用的轉義符:

assert '\t' == '\011'    //Tab,Tab鍵
assert '\n' == '\012' //New line,換行符
assert '\r' == '\015' //Carriage return,回車
assert '\n' == """
""" //Spanning multiple lines,跨越多行

對象的字符串表示:

def object = new Object()
assert String.valueOf(object) == object.toString()  //Objects
assert String.valueOf(true) == true.toString() //Booleans
assert  String.valueOf('a') == 'a'.toString() //Characters
assert String.valueOf(1) ==  1.toString() //Numbers
assert String.valueOf([a:1,b:2]) == [a:1,b:2].toString()  //Collections  

字符串長度:

s = "Hello World"
assert s.size() == 11
assert s.size() == s.length()

填充(pad)字符串:

assert 'Hello'.padRight(7,'*') == 'Hello**'
assert 'Hello'.padLeft(7,'*') ==  '**Hello'
assert 'Hello'.center(9,'*') == '**Hello**'

分解字符串:

s = "The quick brown fox jumps over the lazy dog"
assert s.tokenize()  == ['The','quick','brown','fox','jumps','over','the','lazy','dog']
assert s.tokenize()  == new StringTokenizer(s).collect{it}
s1 =  "The,quick*brown*fox,*jumps*over*the*lazy*dog"
assert s1.tokenize(',*') ==  s.tokenize()

查詢字符串:

alphabets = new String('a' .. 'z' as char[])
assert alphabets.find{it >  'f'} == 'g' //First one found
assert alphabets.findAll{it > 'f'} == 'g'  .. 'z'//ALl found
assert alphabets.findIndexOf{ it > 'f'} ==  alphabets.indexOf('g')
assert alphabets.every {it > 'A'}
assert  alphabets.any{it < 'c'}
assert alphabets.startsWith('abc')
assert  alphabets.endsWith('xyz')
assert alphabets.contains('def')
assert  alphabets.indexOf('c') == 2
assert alphabets.indexOf('d') == alphabets.lastIndexOf ('d')
assert alphabets.count('a') == 1

替換字符串:

s = "Hello"
assert s.replace('H','Y') == 'Yello'
assert s.replace('l','p')  == 'Heppo'

字符串反轉:

s = 'mirror'
assert s.reverse() == 'rorrim'

字符串操作符:

assert 'hello' + ' world' - 'l' == 'helo world' //Subtracts at most one 

l
assert ('Today is Sunday' - 'Sunday').trim() == 'Today is'
assert 'hello  ' * 2 == 'hello hello '
def empty = []
assert 'abc'.each{empty <<  it} == 'abc'
assert 'abc'.next() == 'abd'
assert 'abc'.previous() ==  'abb'

下標操作符:

assert 'hello'[1] == 'e'
assert 'hello'[2..'hello'.size() - 1] ==  'llo'
assert 'hello'[0,2,4] == 'hlo'
assert 'hello'[-4,-2] == 'el'

字符串比較:

assert 'a' < 'b'
assert 'a' > 'A'
assert 'a'.compareTo('b') == - 1
assert 'a'.compareToIgnoreCase('A') == 0

尋找最大值和最小值:

Collections.max('abcdeF'.toList()) == 'e'
assert Collections.max ('abcdeF'.toList(), String.CASE_INSENSITIVE_ORDER) == 'F'
assert Collections.min (['abc','abd','abe']) == 'abc'
assert Collections.min(['Abc','aBd','abE'],  String.CASE_INSENSITIVE_ORDER) == 'Abc'

StringBuffers和StringBuilders是可變的,允許字符串改變。StringBuilder不是線程安全的,因此 處理速度要比StringBuffers快。

def sb = new StringBuffer('Hello World')
assert sb.toString() == 'Hello  World'
sb.length = 5 
assert sb.toString() == 'Hello'
assert sb.substring (0,2) == 'He'
//Use <<, append(String) or leftShift(String) to append to  a StringBuffer.
//Using + to append to a StringBuffer will return a  String
sb = new StringBuffer("Hello")
assert sb + ' World' in  java.lang.String
assert sb << ' World' in java.lang.StringBuffer  
assert sb.toString() == ("Hello World")
assert sb.append(", Groovy  rocks").toString() == "Hello World, Groovy rocks"
assert sb.leftShift(".  Doesn't?").toString() == "Hello World, Groovy rocks. Doesn't?"

您也可以對StringBuffer或StringBuilder使用下標,如:

sb = new StringBuffer("abcdefg")
assert sb[0] == 'a'
assert sb[2..4] ==  'cde'
assert sb[0].class == String
assert sb[-6..-4] == "bcd"
sb[0..2] =  "xyz"
assert sb.toString() == "xyzdefg"

操作StringBuffers:

sb = new StringBuffer("StringBuffers are mutable")
sb.delete(sb.indexOf(" are  mutable"),sb.size())
assert sb.toString() == "StringBuffers"
sb.insert(sb.size (), " are mutable")
assert sb.toString() == "StringBuffers are  mutable"
sb.replace(sb.indexOf("StringBuffers"), "StringBuffers".size(),  "StringBuilders")
assert sb.toString() == "StringBuilders are mutable"
def  string = new String(sb)
def string2 = string.replaceAll("StringBuilders",  "StringBuffers")
assert string2 == "StringBuffers are mutable"

正如您看到的,GDK在java.lang.String,java.lang.StringBuffer和java.lang.StringBuilder基礎 上添加了很多實用的方法。前面的例子只討論部分方法,因此推薦您查看String的API文檔, http://groovy.codehaus.org/groovy-jdk/java/lang/String.html;StringBuffer, http://groovy.codehaus.org/groovy-jdk/java/lang/StringBuffer.html; StringBuilder, http://groovy.codehaus.org/groovy-jdk/java/lang/StringBuilder.html。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved