首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Ruby 字串核心 API 速查表 (長度、檢索、插入、分割、替換、刪除、反轉等)

     編輯:Java 相關知識

原標題「JAVA 幫助文檔 JDK 1.5/1.6/1.7」與內容完全不符。實際為 **Ruby String 類別核心方法** 的詳細中文速查筆記,涵蓋長度、子字串檢測、插入、分割、替換、刪除、去空白、比對、反轉、去重、轉數字等 11 大類操作,並附帶 chomp/chop 差異與 split/scan 對比。

1. 取得長度

str.length  # => Integer
"hello".length  # => 5

2. 檢測是否包含子字串/字元

str.include?(other_str)  # => true/false
"hello".include?("lo")   # => true
"hello".include?("ol")   # => false
"hello".include?('h')    # => true  # 字元也可

3. 插入字串 (insert)

str.insert(index, other_str)  # => str (修改原字串)
"abcd".insert(0, 'X')   # => "Xabcd"
"abcd".insert(3, 'X')   # => "abcXd"
"abcd".insert(-3, 'X')  # => "abXcd"  # 負索引從尾部計算

4. 分割字串 (split)

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"]          # 限制段數

5. 替換字串 (gsub / replace)

# 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"

6. 刪除字元 (delete)

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

7. 去除首尾空白

str.lstrip  # => new_str (僅左側)
" hello ".lstrip  # => "hello "
"hello".lstrip    # => "hello"
# 另有 rstrip (右側)、strip (雙側)

8. 正則比對 (match)

str.match(pattern)  # => MatchData / nil
"abc123".match(/\d+/)  # => #

9. 反轉字串 (reverse)

str.reverse  # => new_str
"stressed".reverse  # => "desserts"

10. 擠壓重複字元 (squeeze)

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" # 指定範圍

11. 轉換為整數 (to_i)

str.to_i  # => Integer
"12345".to_i  # => 12345
"abc".to_i    # => 0 (無數字前綴回傳 0)

chomp vs chop 差異

方法行為範例
chomp移除尾部 \n、\r、\r\n (可指定參數移除特定尾綴)"hello\n".chomp #=> "hello"
chop無條件移除**最後一個字元** (無論是否換行)"hello".chop #=> "hell"

split 進階:保留分隔符

# 正則含捕獲組 () 會保留分隔符
"Three little words".split(/\s+/)     # => ["Three", "little", "words"]
"Three little words".split(/(\s+)/)   # => ["Three", " ", "little", " ", "words"]

split vs scan

  • split(pattern):pattern 為分隔符,回傳分割後的欄位。
  • scan(pattern):pattern 為欲擷取的內容,回傳所有匹配片段。
"123=342=4234".scan(/\d+/)  # => ["123", "342", "4234"]
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved