You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Ballerina中实现按字符串后缀数字排序的自定义排序?

在Ballerina中按字符串后缀数字排序数组

你遇到的问题是sort函数的参数用法不对,Ballerina的sort函数如果要自定义排序规则,需要传递比较函数,而不是提取键的函数。以下是正确的实现方式:

步骤1:编写比较逻辑

我们需要先从每个字符串中提取-后面的数字,再比较这两个数字的大小。

完整代码示例

import ballerina/io;

public function main() {
    string[] arr = ["abcd-4", "abcd-1", "abcd-3", "abcd-2"];
    
    // 升序排序
    string[] sortedAsc = arr.sort(function(string a, string b) returns int {
        int numA = int:parse(a.split("-")[1]);
        int numB = int:parse(b.split("-")[1]);
        return numA - numB;
    });
    
    // 降序排序(只需反转比较结果)
    string[] sortedDesc = arr.sort(function(string a, string b) returns int {
        int numA = int:parse(a.split("-")[1]);
        int numB = int:parse(b.split("-")[1]);
        return numB - numA;
    });
    
    io:println("升序排序结果: ", sortedAsc);
    io:println("降序排序结果: ", sortedDesc);
}

代码说明

  • split("-")将字符串按-分割成数组,取索引1的元素就是后缀数字部分
  • int:parse()将字符串数字转为整数,方便数值比较
  • 比较函数返回值规则:
    • 返回负数:a排在b前面(升序)
    • 返回正数:b排在a前面(降序)
    • 返回0:两者位置不变

为什么你的代码无法运行?

你传递的是一个返回int的函数,但sort的第二个参数需要的是二元比较函数(接收两个元素,返回int),而不是提取单个元素键的函数,这是参数类型不匹配导致的错误。

内容的提问来源于stack exchange,提问作者Nareash Vijayaragavan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 17:36:04