如何在Ruby中的第n个字符后有效地拆分非常长(数百万个字符)的字符串?

时间:2019-04-23 17:35:15

标签: arrays ruby string split

假设我有一个字符串

string = "hellohellohey"

我想每隔2个字符对其进行拆分,所以它看起来像这样

string = ["he","ll","oh","el","lo","he","y"]

我尝试使用scan(/.{2}/)方法,但是如果无法将数组项除以2,它将无法正常工作。

编辑:有必要告知您2个字符的例子。我正在做大事,所以我将每8个百万个字符分割。因此,将其拆分为单个字符并使用each_slice在这里不起作用。它只是冻结了我的笔记本电脑。

3 个答案:

答案 0 :(得分:3)

您可以像下面这样链接多个方法:

string = 'hellohellohey'
string.chars.each_slice(2).map { |s| s.join }
# => ["he", "ll", "oh", "el", "lo", "he", "y"]

#chars会将字符串转换为字符数组。

#each_slice将数组拆分为所需数量的部分。

更新-没有中间/临时数组

根据评论,由于有了@Cary Swoveland,可以避免出现以下临时数组。

string.each_char.each_slice(2).map { |s| s.join }

#each_char给出每个字符的枚举器。

答案 1 :(得分:3)

点匹配除换行符以外的任何字符。您尝试匹配任意字符的2倍,并且如果字符串长度为奇数,则该字符将不匹配最后一个字符。

您可以使用贪婪的quantifier {1,2},因此它首先尝试匹配2次。

.{1,2}

请参见a demo

如果只想匹配小写字母a-z,则也可以使用[a-z]代替点。

答案 2 :(得分:3)

处理(非常)大字符串时,将它们包装在StringIO中可能很有用。它提供了对字符串的类似于文件的有效访问。

例如,您可以通过StringIO#each来读取每个 n 个字符:

public class Admin {

    private Scanner scan;
    private Attendants attendant;
    private ZoneCost zoneCost;
    private Database database;

    Admin() {
        scan = new Scanner(System.in);
        attendant = new Attendants();
        zoneCost = new ZoneCost();
        database = new Database();
        zoneCost.load();
        attendant.load();
        database.load();
    }

输出:

string = "hellohellohey"
string_io = StringIO.new(string)

string_io.each(5) do |substring|
  p substring
end