Ruby: String Handling functions

Source: Internet
Author: User
Tags chop



String handling functions
1. Returns the length of a string


Str.length = integer





2. Determine if the string contains another string


str.include? other_str => true or false
"hello".include? "lo"   #=> true
"hello".include? "ol"   #=> false
"hello".include? ?h     #=> true

 





3. String insertion:


str.insert(index, other_str) => str
"abcd".insert(0, ‘X‘)    #=> "Xabcd"
"abcd".insert(3, ‘X‘)    #=> "abcXd"
"abcd".insert(4, ‘X‘)    #=> "abcdX"
"abcd".insert(-3, ‘X‘)
-3, ‘X‘)   #=> "abXcd"
"abcd".insert(-1, ‘X‘)   #=> "abcdX"





4. String separation, default delimiter is a space


str.split(pattern=$;, [limit]) => anArray
" 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"]
"hi mom".split(%r{\s*})         #=> ["h", "i", "m", "o", "m"]
"mellow yellow".split("ello")   #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(‘,‘)         #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(‘,‘, 4)      #=> ["1", "2", "", "3,4,,"]





5. String substitution


str.gsub (pattern, replacement) => new_str
str.gsub (pattern) {| match | block} => new_str
"hello" .gsub (/ [aeiou] /, ‘*‘) # => "h * ll *" #Replace vowels with *
"hello" .gsub (/ ([aeiou]) /, '<\ 1>') # => "h <e> ll <o>" #Add vowels with angle brackets, \ 1 means to keep the original character ???
"hello" .gsub (/./) {| s | s [0] .to_s + ‘‘} # => "104 101 108 108 111"


String Substitution Two:


str.replace(other_str) => str
s = "hello"         #=> "hello"
s.replace "world"   #=> "world"





6. String deletion:


str.delete([other_str]+) => new_str
"hello".delete "l","lo"        #=> "heo"
"hello".delete "lo"            #=> "he"
"hello".delete "aeiou", "^e"   #=> "hell"
"hello".delete "ej-m"          #=> "ho"





7. Remove the front and rear spaces


str.lstrip => new_str
" hello ".lstrip   #=> "hello "
"hello".lstrip       #=> "hello"





8. String Matching


Str.match (pattern) = Matchdata or nil





9. String inversion


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





10. Remove the duplicate characters


str.squeeze ([other_str] *) => new_str
"yellow moon" .squeeze # => "yelow mon" #Remove all duplicate characters from the string by default
"now is the" .squeeze ("") # => "now is the" #remove duplicate spaces in the string
"putters shoot balls" .squeeze ("m-z") # => "puters shot balls" #Remove duplicate characters in the specified range





11. Convert to Digital


str.to_i=> str
"12345".to_i             #=> 12345





The difference between chomp and chop:
Chomp: remove \ n or \ r at the end of the string
Chop: Removes the last character at the end of a string, whether \n\r or ordinary characters


"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r\n".chomp        #=> "hello"
"hello\n\r".chomp        #=> "hello\n"
"hello\r".chomp          #=> "hello"
"hello".chomp("llo")     #=> "he"

"string\r\n".chop   #=> "string"
"string\n\r".chop   #=> "string\n"
"string\n".chop     #=> "string"
"string".chop       #=> "strin"


Split is a class method of the String class, and I simply translate it based on what RI String.Split provides.



-----------------------------------------------------------String#split



Str.split (pattern=$;, [limit]) = Anarray



------------------------------------------------------------------------



Divides _str_ to substrings based on a delimiter, returning an



Array of these substrings.



Divides a string into substrings with a delimiter and returns an array containing those substrings.






If _pattern_ is a +string+ and then its contents be used as the



Delimiter when splitting _str_. If _pattern_ is a single space,



_str_ is split on whitespace, with leading whitespace and runs of



contiguous whitespace characters ignored.



If the pattern part is a string, it is separated by a delimiter, and if pattern is a space, it is split in spaces and the adjacent spaces are ignored.






If _pattern_ is a +regexp+, _str_ is divided where the pattern



Matches. Whenever the pattern matches a zero-length string, _str_



is split into individual characters.



If pattern is a regular table , split where pattern is matched, and when pattern is a string of length 0, split splits the string into a single character






If _pattern_ is omitted, the value of +$;+ is used. If +$;+ is



+nil+ (which is the default), _str_ was split on whitespace as if '



' were specified.



If pattern is ignored, it will be separated by $, if $; no setting (that is, in the default state), split will make a space '



If the _limit_ parameter is omitted, trailing null



Suppressed. If _limit_ is a positive



Fields would be returned (if _limit_ are +1+, the entire string is)



Returned as the entry in an array). If negative, there is no



Limit to the number of fields returned, and trailing null fields



is not suppressed.



If the limit parameter is ignored, the tracking empty segment is suppressed, and if limit is a positive number, then at most the limit field is returned (if 1, the entire string is returned as a field), and if it is a negative number, the tracking empty segment is not suppressed.






"Now's the time". Split #=> ["Now ' s", "the", "Time"]



"Now's the Time". Split (') #=> ["Now ' s", "the", "Time"]



"Now's the Time". Split (//) #=> ["", "Now", "" "," 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"]



"Hi Mom". Split (%r{\s*}) #=> ["H", "I", "M", "O", "M"]






"Mellow Yellow". Split ("Ello") #=> ["M", "W y", "W"]



"1,2,,3,4,". Split (', ') #=> ["1", "2", "", "3", "4"]



"1,2,,3,4,". Split (', ', 4) #=> ["1", "2", "", "3, 4,,"]



"1,2,,3,4,,". Split (', ',-4) #=> ["1", "2", "", "3", "4", "", ""]






If you include special characters, be aware of escaping



"Wo | Shi | Yi | GE | Bing ". Split (/\s*\|\s*) #竖杠别忘了转义






And the difference between it and String.scan, the pattern in Split is a delimiter, and the pattern in scan refers to something to match.






"123=342=4234=523421=6424". Scan (/\d+/) #=> ["123", "342", "4234", "523421", "6424"]









If the match is enclosed, the delimiter is preserved, for example:






"Three Little Words". Split (/\s+/) #===>["Three", "little", words "]



"Three Little Words". Split (/(\s+)/) #===>["three", "", "Little", "", "words"] reserved spaces



Ruby: String Handling functions


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.