tokenize and split in groovy

Posted By : Abhinav Anand | 27-Dec-2014

There are two methods that represent same things, but they are different .I am going to explain you the facts here.

 

1.The basic difference is, split() method returns String [] instance where as tokenize() returns List instance

2.tokenize() which returns a list ,ignores empty String(when a delimeter appears twice in succession)  but split() keeps such string.

 

String testingString = 'hello Abhinav'
assert testingString .split() instanceof String[]
assert ['hello','Abhinav']==testingString.split() //split with no arguments
assert['he','','o Abhinav']==testingString.split('l')
// split keeps empty string
assert testingString.tokenize() instanceof List
assert ['hello','Abhinav']==testingString.tokenize() //tokenize with no arguments
assert ['he','o Abhinav']==testingString.tokenize('l')
//tokenize ignore empty string

 

3. The tokenize() method uses each character of a String as delimeter where as split() uses the whole string as delimeter.

String  testingString='hello raman'
assert ['hel',' raman']==testingString.split('lo')
assert ['he',' r','m','n']==testingString.tokenize('lo')

4. The split() method takes regex as delimeter but tokenize() doesn't.

String testingString='hello world 123 Abhinav'
assert['hello world ',' Abhinav']==testingString.split(/\d{3}/)

Hope this will be useful to you. Keep visiting for latest blogs.

 

About Author

Author Image
Abhinav Anand

Abhinav is a bright web developer with expertise in groovy and grails frameworks. His hobbies are listening music and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..