## Example of String class using S3 methods. ## similar to String class in ruby. ## some functions from xtable code ## make a String object string <- function(x) { if (!is.String(x)) { x = as.character(x) class(x) <- "String" } return(x) } ## test if a String object is.String <- function(x) return(class(x) == "String") ## give some basic definitions: length, summary, show, print ## give the length length.String <- function(x,...) return(nchar(x)) summary.String <- function(x,...) return(table(strsplit(x,""))) print.String <-function(x,...) cat(x,"\n") ## some methods for access the String slice = function(x,index) UseMethod("slice") slice.String <- function(x,index) { tmp = unlist(strsplit(x,""))[index] return(string(paste(tmp,sep="",collapse=""))) } ## Concatanation concat = function(x,y,sep="") UseMethod("concat") concat.String = function(x,y,sep="") { x <- string(paste(x,string(y),sep=sep)) return(x) } ## repeat a String rept.String = function(x,n) string(paste(rep(x,n),sep="",collapse="")) ## split a String. Return a vector of character type. Can't ## return a vector of "String" type, only a list. split.String <- function(x,y="") unlist(strsplit(x,y)) ## upcase/downcase upcase = function(x) UseMethod("upcase") upcase.String <- function(x) toupper(x) downcase = function(x) UseMethod("downcase") downcase.String <- function(x) tolower(x) ## syntactical shortcuts "[.String" <- function(x,index) slice(x,index) "+.String" <- function(x,y) concat.String(x,y) "*.String" <- function(x,y) rep.String(x,y) "/.String" <- function(x,y) split.String(x,y)