代码之家  ›  专栏  ›  技术社区  ›  Blank Reaver

在文本中用*替换指定短语

  •  1
  • Blank Reaver  · 技术社区  · 7 年前

    我的目的是接受文本的一段,并找到我要编辑或替换的特定短语。

    我创建了一个方法,该方法将参数作为文本字符串接受。我将该字符串分解为单个字符。将比较这些字符,如果它们匹配,我会将这些字符替换为 *

    def search_redact(text)
      str = ""
    
      print "What is the word you would like to redact?"
      redacted_name = gets.chomp
      puts "Desired word to be REDACTED #{redacted_name}! "
      #splits name to be redacted, and the text argument into char arrays
      redact = redacted_name.split("")
      words = text.split("")
    
      #takes char arrays, two loops, compares each character, if they match it 
      #subs that character out for an asterisks
      redact.each do |x|
        if words.each do |y|
          x == y
          y.gsub!(x, '*') # sub redact char with astericks if matches words text
           end # end loop for words y
        end # end if statment
     end # end loop for redact x
    
    # this adds char array to a string so more readable  
    words.each do |z|
      str += z
    end
    # prints it out so we can see, and returns it to method
      print str
      return str
    end
    
    # calling method with test case
    search_redact("thisisapassword")
    
    #current issues stands, needs to erase only if those STRING of characters are 
    # together and not just anywehre in the document 
    

    如果我输入了一个与文本其他部分共享字符的短语,例如,如果我调用:

    search_redact("thisisapassword")
    

    然后它也将替换该文本。当它接受用户的输入时,我只想去掉文本密码。但它看起来是这样的:

    thi*i**********
    

    请帮忙。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Anthony    7 年前

    这是一个用于在字符串中查找子字符串的经典窗口问题。有很多方法可以解决这个问题,其中一些方法比其他方法效率更高,但我将为您提供一个简单的方法,尽可能多地使用您的原始代码:

    def search_redact(text)
      str = ""
    
      print "What is the word you would like to redact?"
      redacted_name = gets.chomp
      puts "Desired word to be REDACTED #{redacted_name}! "
      redacted_name = "password"
      #splits name to be redacted, and the text argument into char arrays
      redact = redacted_name.split("")
      words = text.split("")
    
      words.each.with_index do |letter, i|
        # use windowing to look for exact matches
        if words[i..redact.length + i] == redact
          words[i..redact.length + i].each.with_index do |_, j|
            # change the letter to an astrisk
            words[i + j] = "*"
          end
        end
      end
    
      words.join
    end
    
    # calling method with test case
    search_redact("thisisapassword")
    

    我们的想法是利用阵列 == 这让我们可以说 ["a", "b", "c"] == ["a", "b", "c"] .现在我们只需遍历输入,然后问这个子数组是否等于另一个子数组。如果它们确实匹配,我们知道需要更改值,因此我们循环遍历每个元素,并将其替换为 *

    推荐文章