center是Ruby中的String類方法,用於將給定字符串的寬度居中。如果指定的寬度大於給定字符串的長度,則此方法將返回指定寬度的新字符串,其中給定字符串居中並填充,否則將僅返回給定字符串。
用法:
str.center(width, padstr='')->new_str
參數:此處,str是給定的字符串,而width是用於將字符串居中的指定寬度。
返回值:此方法可以返回新的修改後的字符串new_str或相同的字符串。
示例1:
#ruby 2.3.1
# Ruby program to demonstrate
# the center method
# Taking a string and
# using the method
puts "String".center(5)
puts "Methods".center(18)
輸出:
String Methods
示例2:
#ruby 2.3.1
# Ruby program to demonstrate
# the center method
# Taking a string and
# using the method
puts "Ruby".center(9, '456')
puts "String Class".center(18, '789')
輸出:
45Ruby456 789String Class789
相關用法
- Scala String ==用法及代碼示例
- Scala String +用法及代碼示例
- Scala String ===用法及代碼示例
- Ruby String chr用法及代碼示例
- Ruby String eql?用法及代碼示例
- Ruby String hex用法及代碼示例
- Scala String =~用法及代碼示例
- Ruby String casecmp?用法及代碼示例
- Ruby String chars()用法及代碼示例
- Ruby String reverse用法及代碼示例
- Ruby String chop!用法及代碼示例
- Ruby String chomp用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 Ruby | String center() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。