我有人输入带有字符串输入的表单。我需要做的是用“AND”(没有引号)替换字符串中的任何空格。最好的方法是什么?
另外,如果我想删除字符串中的所有空格,我将如何进行此操作?
由于
答案 0 :(得分:12)
替换为和:
s = 'this has some whitespace'
s.gsub! /\s+/, ' AND '
=> "this AND has AND some AND whitespace"
完全删除:
s = 'this has some whitespace'
s.gsub! /\s+/, ''
=> "thishassomewhitespace"
答案 1 :(得分:4)
拆分和加入是另一种技术:
s = " a b c "
s.split(' ').join(' AND ')
# => "a AND b AND c"
这样做的优点是忽略了Peter的RE没有的前导和尾随空格:
s = " a b c "
s.gsub /\s+/, ' AND '
# => " AND a AND b AND c AND "
删除空格
s.split(' ').join('')
# or
s.delete(' ') # only deletes space chars
答案 2 :(得分:1)
使用gsub方法替换空格
s = "ajeet soni"
=> "ajeet soni"
s.gsub(" "," AND ")
=> "ajeet AND soni"