I am asked to using base R to create a program where can encrypt text into numbers. I want the index to be A=1, B=2, C=3, and so on. I already able to create program to recognize the text's numbers, but the result only give me unique values. if i put the text as "My name is bla" it not give the repeating character twice and the result is in increasing numbers, not by the text order.
here is the program I created so far
ori_text = tolower(readline(prompt = "Input your text: "))
X = gsub("\\s ","",ori_text)
X = strsplit(X,"")
print(X)
dict= array(letters,dim = length(letters),dimnames = list(1:26))
for(i in X){
txt = (dimnames(dict[(dict%in%i)==TRUE]))
}
txt2=as.integer(unlist(txt))
cat("your encryped text is: ",txt2)
CodePudding user response:
Using match()
will return the index of each letter in x
from a reference (letters
)
X <- strsplit(tolower(gsub("\\s ", "", "hello world")), "")
match(X[[1]], letters)
CodePudding user response:
X = gsub("\\s ","",ori_text)
X = unlist(strsplit(X,""))
print(X)
dict = array(letters, dim = length(letters), dimnames = list(1:26))
txt = character()
for(i in X){
txt = c(txt, names(dict)[dict == i])
}
txt2=as.integer(txt)
cat("your encryped text is: ",txt2)