user3642360
user3642360

Reputation: 792

R - count consecutive alphabets in a string

I want to know the length of maximum number of consecutive alphabets in a string (excluding order). for example:

ashjklmghipo

here we have consecutive alphbets: jklm, ghi, po. The maximum consecutive alphabets are jklm. so the length is 4.

I did the same thing for consecutive digits but dont know how to do this for alphabets. Any helpwill be highly appreciated. TIA :)

Upvotes: 1

Views: 239

Answers (2)

vpz
vpz

Reputation: 1044

I was thinking about how to do it with some matricial operator, but I only solved it with recursive strategy.

I hope it be useful:
OBS: R has a global var called letters

#Get string
x = "ashjklmghipo"

#split in char
l = strsplit(x, "")[[1]]
# sort if you want
# l = sort(l)

# Creating data.frame with inital letter: 'init' and number of consecutives: 'n'
nleters = data.frame(init = l, n = 0)

# Using recursive strategi
kmax = length(l)

for(k in 1:kmax){
  # var letters is sorted in alphabet order
  aux = (letters[letters >= l[k]] == l[k:kmax])
  for(i in 1:length(aux)){
    # test if 
    if(aux[i]){
      nleters[k,"n"] = nleters[k,"n"] + 1
      # in first non consecutive "aplhabet" breaks inner loop
    }else{break()}
  }
}

# print result
nleters[order(-nleters$n),]

Upvotes: 0

Gregor Thomas
Gregor Thomas

Reputation: 146020

Reduce it to a problem you've already solved:

x = "ashjklmghipo"
x_letters = strsplit(x, "")[[1]]
x_digits = match(x_letters, letters)
x_digits
# [1]  1 19  8 10 11 12 13  7  8  9 16 15

No you need to find the maximum number of consecutive digits in x_digits, which you say you already know how to do. (If you need help with that, see this question.)

Upvotes: 2

Related Questions