當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby String count()用法及代碼示例

count是Ruby中的String類方法。在此方法中,每個參數都定義了一組要計數的字符。這些集合的交集定義了要在給定字符串中計數的字符。以插入號^開頭的任何其他字符串均被取反。

用法:str.count(parameter_list)

參數:在這裏,str是給定的字符串。


返回值:字符數。

示例1:

# Ruby program to demonstrate  
# the count method  
       
# Taking a string and  
# using the method 
str = "String Counting"
puts str.count "ing"

輸出:

7

示例2:

# Ruby program to demonstrate  
# the count method  
       
# Taking a string and  
# using the method 
str = "String Counting"
puts str.count "^ing"
  
str2 = "Ruby Method\\r\\n"
  
puts str.count "\\"

輸出:

8
0


相關用法


注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Ruby | String count() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。