Determine if a string has all the same characters: Difference between revisions

m
→‎{{header|R}}: Improved syntax.
m (→‎{{header|R}}: Syntax highlighting.)
m (→‎{{header|R}}: Improved syntax.)
Line 2,725:
 
=={{header|R}}==
<lang rsplus>isAllSame <- function(string)
{
strLength <- nchar(string)
if(length(strLength) > 1)
{
#R has a distinction between the length of a string and that of a character vector. It is a common source
Line 2,736:
stop("This task is intended for character vectors with lengths of at most 1.")
}
else if(length(strLength) == 0)
{
cat("Examining a character vector of length 0.\n")
TRUE
}
else if(strLength == 0)
{
cat("Examining a character vector of length 1, containing an empty string.\n")
Line 2,751:
"which is of length", paste0(strLength, ":"), "\n")
#strsplit outputs a list. Its first element is the vector of characters that we desire.
characters <- strsplit(string, "")[[1]]
#Our use of match is using R's vector recycling rules. Every element is being checked
#against the first.
differentElementIndex <- match(FALSE, characters[1] == characters, nomatch = 0)
if(differentElementIndex == 0)
{
cat("It has no duplicates.\n")
Line 2,763:
{
cat("It has duplicates. ")
firstDifferentCharacter <- characters[differentElementIndex]
cat(sQuote(firstDifferentCharacter), "is the first different character. It has hex value",
sprintf("0x%X", as.integer(charToRaw(firstDifferentCharacter))),
331

edits