文章会有【原创】或者【转载】标示,部分来自Google Baidu的学习结果 {Java/PHP/Python/Ruby/Go}

Ruby字符串split  


string#each每次处理一行
str= "Once upon\na time\nend"
num=0
str.each do |line|  
  num=num+1
  puts "this is line #{num}:#{line}"
end
#
this is line 1:Once upon
this is line 2:a time
this is line 3:end
处理一个字节:
string#each_byte
str="ABC"
str.each_byte { |char| print char, " "  }
#65 66 67
str="ABC"
a=str.scan(/./)
a.each {|element| print element, " "}
#A B C
string#split:
默认分隔符为空格
str="China is a large country."
a=str.split
a.each { |i| print i, "       "  }
China       is       a       large       country.
str="apple, pear, orange, banana"
a=str.split(',')
a.each {|j| print j}
apple pear orange banana
正则表达式作为pattern
str="linons and tigers and bears"
a=str.split(/and/)
a.each {|j| print j}
linons  tigers  bears
split的第二个参数:最大字段参数根据下面规则限制返回的最大字段数:
1.如果省略该参数,则删除末尾的空值项
2.如果该参数是正数,则返回的最大字段数由该参数指定(必要时将余下的字符串填充到最后一个字段中)。保留末尾的空值项。
3.如果该参数是负数,对返回的字段数没有限制,并保留末尾的空值项。
例:
def showlist(list)
  list.each {|l| print "\"#{l}\"", "   "}
  print "\n"
end
str="alpha, beta, gamma,,"
list1=str.split(",")
list2=str.split(",",2)
list3=str.split(",",4)
list4=str.split(",",8)
list5=str.split(",",-1)
showlist(list1)
showlist(list2)
showlist(list3)
showlist(list4)
showlist(list5)
#
"alpha"   " beta"   " gamma"  
"alpha"   " beta, gamma,,"  
"alpha"   " beta"   " gamma"   ","  
"alpha"   " beta"   " gamma"   ""   ""  
"alpha"   " beta"   " gamma"   ""   ""  

本文出自 “李骥平” 博客,请务必保留此出处http://fsjoy.blog.51cto.com/318484/68382