【问题标题】:Determining length of array of strings ignoring commas/periods (letters only)确定忽略逗号/句点的字符串数组的长度(仅限字母)
【发布时间】:2016-03-15 02:24:36
【问题描述】:

我正在尝试找到确定字符串数组中字母数的最佳方法。我正在拆分字符串,然后循环每个单词,然后拆分字母并循环这些字母。

当我确定长度时,我遇到的问题是它也在计算逗号和句点。因此,仅以字母表示的长度是不准确的。

我知道使用正则表达式可能会更短,但我还不太精通。我的代码通过了大多数测试,但我被困在逗号的位置。

E.g. 'You,' should be string.length = "3"

示例代码:

def abbr(str)
  new_words = []
  str.split.each do |word|
    new_word = []
    word.split("-").each do |w| # it has to be able to handle hyphenated words as well
      letters = w.split('')
       if letters.length >= 4
         first_letter = letters.shift
         last_letter = letters.pop
         new_word << "#{first_letter}#{letters.count}#{last_letter}"
       else 
         new_word << w
      end
    end
   new_words << new_word.join('-')
 end
 new_words.join(' ')

我尝试在循环单词之前执行gsub,但这不起作用,因为我不想完全删除逗号。我只是不需要他们被计算在内。

感谢任何启蒙。

【问题讨论】:

  • 我很难确定abbr 方法的用途。您能否证明该方法的示例输入以及您想要返回的内容?如果您只想快速计算字符串中的字母字符:str.scan(/[[:alpha:]]/).length
  • 对不起@LucasNelson - 如果单词长度为 4 或更多,目标是缩写单词。例如。 internationalization = i18n。所以我们得到第一个和最后一个字母,然后计算中间的字母。我更新了代码,我不能扫描,因为它是一个数组(不是专家,所以我可能遗漏了一些东西)
  • @LizGee,您能否提供更多示例?我也不太明白你需要做什么。

标签: ruby-on-rails arrays ruby string


【解决方案1】:
arr = ["Now is the time for y'all Rubiests",
       "to come to the aid of your bowling team."]
arr.join.size
  #=> 74  

没有正则表达式

def abbr(arr)
  str = arr.join
  str.size - str.delete([*('a'..'z')].join + [*('A'..'Z')].join).size
end

abbr arr
  #=> 58

在这里和下面,arr.join 将数组转换为单个字符串。

使用正则表达式

R = /
    [^a-z] # match a character that is not a lower-case letter
    /ix    # case-insenstive (i) and free-spacing regex definition (x) modes

def abbr(arr)
  arr.join.gsub(R,'').size
end

abbr arr
  #=> 58

你当然可以写:

arr.join.gsub(/[^a-z]/i,'').size
  #=> 58

【讨论】:

    【解决方案2】:

    试试这个:

    def abbr(str)
      str.gsub /\b\w+\b/ do |word|
        if word.length >= 4
          "#{word[0]}#{word.length - 2}#{word[-1]}"
        else
          word
        end
      end
    end
    

    gsub 调用中的正则表达式表示“一个或多个单词字符在单词边界之前和之后”。传递给 gsub 的块对每个单词进行操作,块的返回是替换 gsub 中的“单词”匹配项。

    【讨论】:

      【解决方案3】:

      您可以检查每个字符的 ascii 值是在 97-122 还是 65-90。当满足此条件时,增加一个局部变量,该变量将为您提供不带任何数字或任何特殊字符或任何字符串的总长度空白。

      【讨论】:

        【解决方案4】:

        你可以使用类似的东西(短版):

        a.map { |x| x.chars.reject { |char| [' ', ',', '.'].include? char } }
        

        带解释的长版:

        a = ['a, ', 'bbb', 'c c, .']     # Initial array of strings
        excluded_chars = [' ', ',', '.'] # Chars you don't want to be counted
        
        a.map do |str|                   # Iterate through all strings in array
          str.chars.reject do |char|     # Split each string to the array of chars
            excluded_chars.include? char # and reject excluded_chars from it 
          end.size # This returns [["a"], ["b", "b", "b"], ["c", "c"]] 
        end        # so, we take #size of each array to get size of the string
        
        # Result: [1, 3, 2]
        

        【讨论】:

          猜你喜欢
          • 2018-05-20
          • 1970-01-01
          • 1970-01-01
          • 2021-08-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-28
          • 2012-05-23
          相关资源
          最近更新 更多