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

时间:2018-04-19 21:35:46

标签: ruby gsub redaction

我的目的是接受一段文字并找到我想要删除或替换的指定短语。

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

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 个答案:

答案 0 :(得分:1)

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

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"]。所以现在我们只是走输入并询问这个子数组是否等于这个其他子数组。如果它们匹配,我们知道我们需要更改值,以便循环遍历每个元素并将其替换为*