原標題「JAVA 幫助文檔 JDK 1.5/1.6/1.7」與內容完全不符。實際為 **Ruby String 類別核心方法** 的詳細中文速查筆記,涵蓋長度、子字串檢測、插入、分割、替換、刪除、去空白、比對、反轉、去重、轉數字等 11 大類操作,並附帶 chomp/chop 差異與 split/scan 對比。
str.length # => Integer
"hello".length # => 5
str.include?(other_str) # => true/false
"hello".include?("lo") # => true
"hello".include?("ol") # => false
"hello".include?('h') # => true # 字元也可
str.insert(index, other_str) # => str (修改原字串)
"abcd".insert(0, 'X') # => "Xabcd"
"abcd".insert(3, 'X') # => "abcXd"
"abcd".insert(-3, 'X') # => "abXcd" # 負索引從尾部計算
str.split(pattern=$;, [limit]) # => Array
" now's the time".split # => ["now's", "the", "time"] # 預設空白分割
"1, 2.34,56, 7".split(%r{,\s*}) # => ["1", "2.34", "56", "7"] # 正則分割
"hello".split(//) # => ["h", "e", "l", "l", "o"] # 逐字元
"hello".split(//, 3) # => ["h", "e", "llo"] # 限制段數
# gsub: 全域替換,回傳新字串
"hello".gsub(/[aeiou]/, '*') # => "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>') # => "hll" # \1 為捕獲組回參
"hello".gsub(/./) {|s| s.ord.to_s + ' '} # => "104 101 108 108 111 "
# replace: 內容整體置換 (修改原字串)
s = "hello"
s.replace("world") # => "world"
str.delete([other_str]+) # => new_str
"hello".delete("l", "lo") # => "heo" # 刪除 l 或 l/o
"hello".delete("lo") # => "he"
"hello".delete("aeiou", "^e") # => "hell" # 刪除元音但保留 e
"hello".delete("ej-m") # => "ho" # 範圍 e-j, m
str.lstrip # => new_str (僅左側)
" hello ".lstrip # => "hello "
"hello".lstrip # => "hello"
# 另有 rstrip (右側)、strip (雙側)
str.match(pattern) # => MatchData / nil
"abc123".match(/\d+/) # => #
str.reverse # => new_str
"stressed".reverse # => "desserts"
str.squeeze([other_str]*) # => new_str
"yellow moon".squeeze # => "yelow mon" # 全部重複字元擠壓
" now is the".squeeze(" ") # => " now is the" # 僅擠壓空格
"putters shoot balls".squeeze("m-z") # => "puters shot balls" # 指定範圍
str.to_i # => Integer
"12345".to_i # => 12345
"abc".to_i # => 0 (無數字前綴回傳 0)
| 方法 | 行為 | 範例 |
|---|---|---|
chomp | 移除尾部 \n、\r、\r\n (可指定參數移除特定尾綴) | "hello\n".chomp #=> "hello" |
chop | 無條件移除**最後一個字元** (無論是否換行) | "hello".chop #=> "hell" |
# 正則含捕獲組 () 會保留分隔符
"Three little words".split(/\s+/) # => ["Three", "little", "words"]
"Three little words".split(/(\s+)/) # => ["Three", " ", "little", " ", "words"]
split(pattern):pattern 為分隔符,回傳分割後的欄位。scan(pattern):pattern 為欲擷取的內容,回傳所有匹配片段。"123=342=4234".scan(/\d+/) # => ["123", "342", "4234"]