如何根据非标准字母对字符串数组进行排序? [英] How can I sort an array of strings based on a non standard alphabet?

查看:108
本文介绍了如何根据非标准字母对字符串数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按字母顺序对世界语中的短语数组进行排序.有没有办法使用sort_by来做到这一点?

I'm trying to sort an array of phrases in Esperanto by alphabetical order. Is there a way to use sort_by to accomplish this?

我正在对照世界语字母中的字符串索引检查字符串的每个字符,每个增加的索引在排序优先级上都降低了一步:

I'm checking each character of the string against its index in the Esperanto alphabet, with each increasing index being a step lower in sorting priority:

  esp_alph = " abcĉdefgĝhĥijĵklmnoprsŝtuŭvz"
  arr.sort_by {|string|  
    [esp_alph.index(string[0]),
     esp_alph.index(string[1]),
     esp_alph.index(string[2]),
     esp_alph.index(string[3])]}

但是,这不是可扩展的解决方案,如果我的条件多于字符串中的字符,它就会中断.根据我的字符串长度,我似乎正处于循环的风口浪尖,但是我不知道如何在没有语法错误的情况下实现它.还是有解决该问题的更好方法?

However, this isn't a scalable solution, and it breaks if I have more conditions than I have characters in my string. It seems like I'm right at the cusp of a loop based on my string length, but I can't figure out how to implement it without syntax errors. Or is there a better way to go about solving this issue?

推荐答案

只需用ASCII表中的某些字符替换世界语字母中的所有字符,以使世界语字母顺序与ASCII顺序匹配.

Simply replace all characters in the Esperanto alphabet with some characters in the ASCII table so that the Esperanto alphabet order matches the ASCII order.

假设您按给出的顺序输入世界语字母,我认为这些字母应该按以下顺序排列:

Suppose you have the Esperanto alphabets in the order you gave, which I assume are in the order they are supposed to be:

esp_alph = " abcĉdefgĝhĥijĵklmnoprsŝtuŭvz"

并取出长度相同的ASCII字符表的任何部分(请注意\\是单个字符):

and take out any portion of the ASCII character table of the same length (notice that \\ is a single character):

ascii = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\"

ascii = "@-\\"

然后,您可以简单地执行以下操作:

Then, you can simply do:

arr.sort_by{|string| string.tr(esp_alph, ascii)}

在这里,trgsub快,我认为它可以扩展.

Here, tr is faster than gsub, and I think it scales enough.

这篇关于如何根据非标准字母对字符串数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆