Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract longest word in string

I would like to find and extract the longest word of a string, if possible using a tidyverse package.

library(tidyverse)

tbl <- tibble(a=c("ab cde", "bcde f", "cde fg"), b=c("cde", "bcde", "cde"))
tbl
# A tibble: 3 x 1
   a
<chr>
1 ab cde
2 bcde f
3 cde fg

The result I am looking for is:

# A tibble: 3 x 2
   a     b
  <chr> <chr>
1 ab cde   cde
2 bcde f  bcde
3 cde fg   cde

The closest post to the question I have found is this: longest word in a string. Does anyone have an idea for an even simpler way?

like image 808
moabit21 Avatar asked Nov 06 '17 08:11

moabit21


People also ask

How do you find the longest word in a string?

function findLongestWord(str) { var longestWord = str. split(' '). reduce(function(longest, currentWord) { return currentWord. length > longest.

How do you find the longest word in a string python?

Use max python built-in function, using as key parameter the len function. It would iterate over word_list applying len function and then returning the longest one.

How do you find the longest word in a string C++?

To find the smallest and largest word, we will find the length of each word by using two indexes, one for the start of the word and one for the ending which is marked using the ' ' (space character) or '\0' character. Then using the start and end index, we will find the maxLength and minlength.


1 Answers

Solution using base R:

# Using OPs provided data
tbl$b <- sapply(strsplit(tbl$a, " "), function(x) x[which.max(nchar(x))])

Explanation:

  • Split each line into words (strsplit)
  • Determine word length (nchar)
  • Select which word is longest in line (which.max)
like image 137
pogibas Avatar answered Nov 15 '22 09:11

pogibas