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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Abhinav Anand
Abhinav is a bright web developer with expertise in groovy and grails frameworks. His hobbies are listening music and playing cricket.