ruby字串相關方法

來源:互聯網
上載者:User

標籤:des   style   blog   code   java   http   

 

構造字串字面量

方法一:
最簡單的使用單引號或者雙引號括起來的字串,比如"hello"。

方法二:
使用%q配合分界符,%q代表單引號
str=%q!he/lo!

方法三:
使用%Q配合分界符,%Q代表雙引號
str=%Q{he/lo}

方法四:
here document構建字串,該方法比較適合用於多行字串的建立。由<<和邊界字串作為開頭,由邊界字串作為結尾,比如下列代碼:
str = <<END_OF_STRING1
  We are here now,
  where are you?
END_OF_STRING1
puts str
輸出結果為:
  We are here now,
  where are you?

較為複雜的是允許多個邊界字串對出現。
str = <<END_OF_STRING1,<<END_OF_STRING2
  We are here now,
  where are you?
END_OF_STRING1
  I will leave now,
  would you like to go with me?
END_OF_STRING2

puts str
輸出結果為:
  We are here now,
  where are you?
  I will leave now,
  would you like to go with me?

 

連接字串

    + 串連。ruby的+操作符不會將其右側運算元自動轉為字串,你必須親自動手:

planet_number=5
"hello planet #" + planet_number.to_s # to_s converts to str

在ruby中,採用字串插入通常要比採用+操作符串連簡單一些。在字串插入時,對to_s的調用是自動進行的:
"hello planet ##{planet_number}"

字面量與copy-on-write技術

在Java中,如果兩個String對象a和b的值都是"abcdef",如下:
String a="abcdef";
String b="abcdef";
那 麼,JVM只會建立一個常量對象"abcdef",讓a和b都指向它。但是在ruby中,採用了智能指標(熟悉c++的朋友清楚)的一個進階技術 copy-on-write,一開始也是共用同一個字元常量,但是一旦之後某個對象(比如b對象)進行了修改操作,則"abcdef"將產生一個副本,b 的修改操作在這個副本上進行。
更詳細的討論請參考http://developer.51cto.com/art/200811/98630.htm。

和Java的一些其他區別
Java的String每次執行修改操作,都不會改變自身,而是建立一個新的String對象,而Ruby每次的修改操作都會修改自身。

 

計算長度

           puts "hello".length

 

訪問字元和子字串訪問某個元素時返回的有由單個字元組成的字串。
s="hello"
s[0] # "h"
s[s.length-1]
重點:
如果你試圖訪問一個超出了字串末尾的字元,ruby不會拋出異常,只是簡單的返回nil。


賦值:
賦值右側可以是任意一個字串,既可以包含多字元,也可以是Null 字元。
irb(main):067:0> s="hello"
=> "hello"
irb(main):068:0> s[-1]="abc"
=> "abc"
irb(main):069:0> s
=> "hellabc"
irb(main):070:0>

 

s[-s.length]等於s[1]

s[s.length]等於nil

擷取子串:
方括弧中使用有兩個都好分割的運算元,第一個指定index(可以為負的),第二個指定長度值(必須非負)。

s = "hello"
s[0,2] # "he"
s[-1,1] # "o": returns a string, not the character code ?o
s[0,0] # "": a zero-length substring is always empty
s[0,10] # "hello": returns all the characters that are available
s[s.length,1] # "": there is an empty string immediately beyond the end
s[s.length+1,1] # nil: it is an error to read past that
s[0,-1] # nil: negative lengths don‘t make any sense

 

刪除:
賦值非Null 字元串相當於刪除。相應第,如果左側的長度值為0,那麼相當於插入:

s = "hello"
s[0,1] = "H" # Replace first letter with a capital letter
s[s.length,0] = " world" # Append by assigning beyond the end of the string 增加
s[5,0] = "," # Insert a comma, without deleting anything
s[5,6] = "" # Delete with no insertion; s == "Hellod"

Another way to extract, insert, delete, or replace a substring is by indexing a string
with a Range object. We’ll explain ranges in detail in §3.5 later. For our purposes here,
a Range is two integers separated by dots. When a Range is used to index a string, the
return value is the substring whose characters fall within the Range:

s = "hello"
s[2..3] # "ll": characters 2 and 3
s[-3..-1] # "llo": negative indexes work, too
s[0..0] # "h": this Range includes one character index

s[0...0] # "": this Range is empty
s[2..1] # "": this Range is also empty
s[7..10] # nil: this Range is outside the string bounds
s[-2..-1] = "p!" # Replacement: s becomes "help!"
s[0...0] = "Please " # Insertion: s becomes "Please help!"
s[6..10] = "" # Deletion: s becomes "Please!"

 

Don’t confuse string indexing with two comma-separated integers with this form that
uses a single Range object. Although both involve two integers, there is an important
difference: the form with the comma specifies an index and a length; the form that uses
a Range object specifies two indexes.

還可以用一個字串來索引另一個字串。

It is also possible to index a string with a string. When you do this, the return value is
the first substring of the target string that matches the index string, or nil, if no match
is found. This form of string indexing is really only useful on the lefthand side of an
assignment statement when you want to replace the matched string with some other
string:
s = "hello" # Start with the word "hello"
while(s["l"]) # While the string contains the substring "l"
 s["l"] = "L"; # Replace first occurrence of "l" with "L"
end # Now we have "heLLo"
Finally, you can index a string using a regular expression. (Regular expression objects
are covered in §9.2.) The result is the first substring of the string that matches the
pattern, and again, this form of string indexing is most useful when used on the
lefthand side of an assignment:
s[/[aeiou]/] = ‘*‘ # Replace first vowel with an asterisk

 

 

對字串進行迭代

 

 

更多:

http://blog.csdn.net/csfreebird/article/details/4646140

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.