//see: http://groovyconsole.appspot.com/edit/1032002
String generateToken(Integer size = 16){
String availableChars = 'ABCDEFGHIJLMNOPQRSTUVXZYabcdefghijlmnopqrstuvxzy0123456789!@#$%*_'
Random generator = new Random()
String token = ""
size.times {
token += availableChars[generator.nextInt(availableChars.length() - 1)]
}
return token
}
generateToken()
generateToken(8)
Showing posts with label string. Show all posts
Showing posts with label string. Show all posts
Wednesday, July 24, 2013
Random String generator
Sunday, January 6, 2013
String padding with zeros
String.metaClass.zeropad = { Integer padding = 0 ->
return ("0" * Math.max(0, (padding ?: 0) - delegate.size())) + delegate
}
Integer.metaClass.zeropad = { Integer padding = 0 ->
return delegate.toString().zeropad(padding)
}
assert "123".zeropad() == "123"
assert "123".zeropad(null) == "123"
assert "123".zeropad(5) == "00123"
assert "1234".zeropad(5) == "01234"
assert "12345".zeropad(5) == "12345"
assert "123456".zeropad(5) == "123456"
assert 123.zeropad() == "123"
assert 123.zeropad(null) == "123"
assert 123.zeropad(5) == "00123"
assert 1234.zeropad(5) == "01234"
assert 12345.zeropad(5) == "12345"
assert 123456.zeropad(5) == "123456"
Tuesday, March 29, 2011
Category - Advanced
class StringCategory {
static String camelize(String self) {
def newName = self.split("_").collect() {
it.substring(0, 1).toUpperCase() + it.substring(1, it.length())
}.join()
newName[0..<1].toLowerCase() + newName[1..-1]
}
static Integer getPm(Integer self) {
(self == 12 ? 12 : self + 12)
}
static Integer getAm(Integer self) {
self == 12 ? 0 : self
}
}
class SpeakCategory {
static String shout(String self) { // Method argument is String, so we can add shout() to String object.
self.toUpperCase() + '!!'
}
static String whisper(String self, boolean veryQuiet = false, Integer a = 0) {
"${veryQuiet ? 'sssssssh' : 'sssh'}.. $self $a"
}
static String army(String self) {
"$self. Sir, yes sir!"
}
}
use (StringCategory) {
println 'Hi_there_fella'.camelize()
println 12.am + ' o\'clock'
println 2.pm + ' o\'clock'
}
use (SpeakCategory) {
println "Pay attention".shout()
println "Be vewy, vewy, quiet.".whisper()
println "Be vewy, vewy, quiet.".whisper(true, 1)
println "Groovy rocks".army()
}
// Or we can use the @Category annotation.
// implicit 'this', no 'self' arg passed in
@Category(String)
class StreetTalk {
String hiphop(Integer times = 1) {
"Yo, yo, here we go! " * times + "${this}"
}
}
use(StreetTalk) {
println 'Groovy is dope!'.hiphop(2)
}
http://groovyconsole.appspot.com/script/448002
Subscribe to:
Comments (Atom)