如何根据 JAVA 中存在的整数值对字符串进行排序

How to sort strings based on the integer value present inside it in JAVA

假设我有不同的字符串集,例如:

字符串 1 :- 2021 年印度国际象棋联赛 在线(在家玩) 电子竞技 价格99起

字符串 2 :- 每周国际象棋 Maha Muqabla 在线(在家玩) 电子竞技 价格225起

字符串 3 :- 使命召唤手游锦标赛 在线(在家玩) 电子竞技 价格300起

字符串 4 :- 绿色 10 公里挑战赛——获得印度最大的奖牌 你的地方和你的时间:印度 电子竞技 价格 399

字符串 5 :- Free Fire Solo 和 Squad(百慕大) 在线(在家玩) 电子竞技 价格100起

*字符串 6 :- 约翰逊使命召唤移动锦标赛 在线(在家玩) 电子竞技 价格100起

字符串 8 :- 在家为孩子们提供在线武术辅导 在线串流 混合武术 价格1180起

字符串 9:- 帮助视力保护者的使命召唤大逃杀 在线(在家玩):印度 电子竞技 价格 100

在这里,我根据价格按升序打印字符串,那么我该怎么做呢。

提前致谢。 :) 首选语言是 JAVA

您可以使用比较器并删除所有非数字字符,然后比较这些数字并相应地对它们进行排序。也许这可以为您指明正确的方向:Sorting Strings that contains number in Java

您可以在 Java 中执行以下操作:

    strings.stream()
            .sorted(Comparator.comparingDouble(s -> {
                int priceIndex = s.indexOf("price") + "price ".length();
                int spaceAfterPrice = s.indexOf(" ", priceIndex);
                int endPriceIndex = spaceAfterPrice != -1 ? spaceAfterPrice:s.length();
                return Double.parseDouble(s.substring(priceIndex, endPriceIndex));
            }))
            .forEach(System.out::println);

输出:

Indian Chess League 2021 Online (Play From Home) E Sports price 99 onwards
Free Fire Solo And Squad (Bermuda) Online (Play From Home) E Sports price 100 onwards
Johnson Call Of Duty Mobile Tournament Online (Play From Home) E Sports price 100 onwards
Call of Duty Battle Royale In Aid Of Sightsavers Online(Play From Home):India E Sports price 100
Weekly Chess Maha Muqabla Online (Play From Home) E Sports price 225 onwards
Call of Duty Mobile Tournament Online (Play From Home) E Sports price 300 onwards
Green 10KM Challenge – Get India`s Biggest Medal Your Place and Your Time: India E Sports price 399
Online Martial Arts Coaching for Kids at Home Online Streaming Mixed Martial Arts price 1180 onwards