我用几个测试用例编写了这个函数:
characterCounter <- function(char1, char2) {
if(is.null(char1) || is.null(char2)) {
print("Please check your character sequences!")
return()
}
if(nchar(char1, type = "chars") < nchar(char2, type = "chars") || nchar(char1, type = "chars") <= nchar(char2, type = "chars")) {
cat(sprintf("%s is smaller or smaller-equal than %s\n", char1 , char2))
return()
} else if(nchar(char1, type = "chars") > nchar(char2, type = "chars") || nchar(char1, type = "chars") >= nchar(char2, type = "chars")) {
cat(sprintf("%s is greater or greater-equal than %s\n", char1 , char2))
return()
} else if(nchar(char1, type = "chars") == nchar(char2, type = "chars")) {
cat(sprintf("%s is equal to %s\n", char1, char2))
return()
}
}
#Testcases
(characterCounter("Hello","Hell"))
(characterCounter("Wor","World"))
但是,在每种情况下,我都会回来:
> (characterCounter("Hello","Hell"))
Hello is greater or greater-equal than Hell
NULL
> (characterCounter("Wor","World"))
Wor is smaller or smaller-equal than World
NULL
我不喜欢我的输出是尾随NULL
. 为什么我要把这个拿回来?(字符计数器(NULL,NULL))
更新
characterCounter <- function(char1, char2) {
if(is.null(char1) || is.null(char2)) {
return(cat("Please check your character sequences!"))
}
if(nchar(char1, type = "chars") < nchar(char2, type = "chars") || nchar(char1, type = "chars") <= nchar(char2, type = "chars")) {
return(cat(sprintf("%s is smaller or smaller-equal than %s\n", char1 , char2)))
} else if(nchar(char1, type = "chars") > nchar(char2, type = "chars") || nchar(char1, type = "chars") >= nchar(char2, type = "chars")) {
return(cat(sprintf("%s is greater or greater-equal than %s\n", char1 , char2)))
} else if(nchar(char1, type = "chars") == nchar(char2, type = "chars")) {
return(cat(sprintf("%s is equal to %s\n", char1, char2)))
}
}