检查字符串是否包含一个或多个单词

时间:2013-10-06 19:27:16

标签: ruby string whitespace

当循环文本行时,最好的方法(大多数“Ruby”)做一个if else语句(或类似的)以检查字符串是否是单个单词是什么?

def check_if_single_word(string)
   # code here
end

s1 = "two words"
s2 = "hello"

check_if_single_word(s1) -> false
check_if_single_word(s2) -> true

5 个答案:

答案 0 :(得分:5)

既然你问的是“最Ruby”方式,我会把方法重命名为single_word?

一种方法是检查是否存在空格字符。

def single_word?(string)
  !string.strip.include? " "
end

但是如果你想允许符合你的单词定义的特定字符集,可能包括撇号和连字符,请使用正则表达式:

def single_word?(string)
  string.scan(/[\w'-]+/).length == 1
end

答案 1 :(得分:2)

按照您对评论中给出的单词的定义:

[A] stripped string that doesn't [include] whitespace

代码将是

def check_if_single_word(string)
  string.strip == string and string.include?(" ").!
end

check_if_single_word("two words") # => false
check_if_single_word("New York") # => false
check_if_single_word("hello") # => true
check_if_single_word(" hello") # => false

答案 2 :(得分:1)

我会检查字符串中是否有空格。

def check_if_single_word(string)
   return !(string.strip =~ / /)
end

.strip将删除字符串开头和结尾可能存在的多余空格。

!(myString =~ / /)表示该字符串与单个空格的正则表达式不匹配。 同样,您也可以使用!string.strip[/ /]

答案 3 :(得分:1)

这里有些代码可以帮助你:

def check_if_single_word(string)
   ar = string.scan(/\w+/)
   ar.size == 1 ? "only one word" : "more than one word"
end

s1 = "two words"
s2 = "hello"
check_if_single_word s1 # => "more than one word"
check_if_single_word s2 # => "only one word"

def check_if_single_word(string)
   string.scan(/\w+/).size == 1
end

s1 = "two words"
s2 = "hello"
check_if_single_word s1 # => false
check_if_single_word s2 # => true

答案 4 :(得分:0)

Ruby Way。扩展课程String

class String

  def one?
    !self.strip.include? " "
  end

end

然后使用"Hello world".one?检查字符串是否包含一个或多个单词。

相关问题