如何使用第一个逗号将字符串拆分为段落? [英] How to split string into paragraphs using first comma?
问题描述
我有字符串:@address = "10 Madison Avenue, New York, NY - (212) 538-1884"
像这样拆分它的最佳方法是什么?
I have string: @address = "10 Madison Avenue, New York, NY - (212) 538-1884"
What's the best way to split it like this?
<p>10 Madison Avenue,</p>
<p>New York, NY - (212) 538-1884</p>
推荐答案
String#split 有第二个参数,结果数组中返回的最大字段数:http://ruby-doc.org/core/classes/String.html#M001165
String#split has a second argument, the maximum number of fields returned in the result array: http://ruby-doc.org/core/classes/String.html#M001165
@address.split(",", 2)
将返回一个包含两个字符串的数组,在第一次出现,"时进行拆分.
@address.split(",", 2)
will return an array with two strings, split at the first occurrence of ",".
它的其余部分只是使用插值来构建字符串,或者如果您想让它更通用,例如 Array#map
和 #join
的组合
the rest of it is simply building the string using interpolation or if you want to have it more generic, a combination of Array#map
and #join
for example
@address.split(",", 2).map {|split| "<p>#{split}</p>" }.join("\n")
这篇关于如何使用第一个逗号将字符串拆分为段落?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!