HarmonyOS鸿蒙Next中多语言排序(中文排序)

HarmonyOS鸿蒙Next中多语言排序(中文排序) https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V14/i18n-sorting-local-V14

// 导入模块
import { intl } from '@kit.LocalizationKit';

// 创建排序对象
let options: intl.CollatorOptions = {
   localeMatcher: "lookup", 
   usage: "sort",
   sensitivity: "case" // 区分大小写
};
let collator = new intl.Collator("zh-CN", options);

// 区分大小写排序
let array = ["app", "App", "Apple", "ANIMAL", "animal", "apple", "APPLE"];
array.sort((a, b) => {
   return collator.compare(a, b);
})
console.log("result: ", array);  // animal ANIMAL app App apple Apple APPLE

// 中文拼音排序
array = ["苹果", "梨", "香蕉", "石榴", "甘蔗", "葡萄", "橘子"];
array.sort((a, b) => {
   return collator.compare(a, b);
})
console.log("result: ", array);  // 甘蔗,橘子,梨,苹果,葡萄,石榴,香蕉

// 按笔画排序
options = {
   localeMatcher: "lookup", 
   usage: "sort",
   collation: "stroke"
};
collator = new intl.Collator("zh-CN", options);
array = ["苹果", "梨", "香蕉", "石榴", "甘蔗", "葡萄", "橘子"];
array.sort((a, b) => {
   return collator.compare(a, b);
})
console.log("result: ", array);  // 甘蔗,石榴,苹果,香蕉,梨,葡萄,橘子

// 搜索匹配的字符串
options = {
   usage: "search",
   sensitivity: "base"
};
collator = new intl.Collator("tr", options);
let sourceArray = ['Türkiye', 'TüRkiye', 'salt', 'bright'];
let s = 'türkiye';
let matches = sourceArray.filter(item => collator.compare(item, s) === 0);
console.log(matches.toString());  // Türkiye,TüRkiye

更多关于HarmonyOS鸿蒙Next中多语言排序(中文排序)的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

HarmonyOS Next中多语言排序通过Intl.Collator实现中文排序。该API支持locale参数设置为’zh-CN’,启用拼音排序规则。使用compare方法对中文字符串数组进行排序,默认按拼音字母顺序排列。可通过sensitivity选项控制排序精度,支持区分声调等细化设置。

更多关于HarmonyOS鸿蒙Next中多语言排序(中文排序)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,通过@kit.LocalizationKitCollator类可以实现中文排序,支持拼音和笔画两种方式。使用locale: "zh-CN"指定中文环境,通过collation参数选择排序规则:默认拼音排序("default"或省略),或笔画排序("stroke")。示例代码展示了如何对中文字符串数组按拼音或笔画排序,调用collator.compare(a, b)作为排序回调即可实现正确的本地化排序顺序。

回到顶部