1

So I have a string and I need to find the word which matches two constraints viz, the number of characters in the word should be even and it should be the longest such word.

For ex:

Input: I am a bad coder with good logical skills
Output: skills

Just starting off with R so any help would be great.

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
void
  • 36,090
  • 8
  • 62
  • 107
  • This question covers part of your post: [Extract longest word in string](https://stackoverflow.com/questions/47132629/extract-longest-word-in-string), you just need to subset even numbers and pick the largest one. – pogibas Sep 09 '18 at 08:18
  • @PoGibas thats correct! Thanks.. could you tell me how can I calculate this subset? – void Sep 09 '18 at 08:19
  • First, write a program to find the longest word in a string. If you can do that, then modify it to ignore the words that have an an odd number of characters. – Kaz Nov 07 '18 at 03:25

2 Answers2

2

you can try the library tokenizers

library(tokenizers)

text <- "I am a bad coder with good logical skills"

names(which.max(sapply(Filter(function(x) nchar(x) %% 2 == 0, 
                          unlist(tokenize_words(text))), nchar)))

#[1] "skills" 
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
0

Here is my code:

input<-"I am a bad coder with good logical skills"

words<-strsplit(input," ")                                      # Split it to words

countWords<-sapply(words,nchar)                                 # Count the length of words

dt<-data.frame( word=unlist(words), length=unlist(countWords) ) # Make a dataframe

dt<-dt[order(dt$length),]                                       # Sort the dataframe based on length

dt<-dt[  which((dt$length %% 2)==1),]                           # Get the words with odd length

dt[nrow(dt),]                                                   # Get the longest word
Sal-laS
  • 11,016
  • 25
  • 99
  • 169