gpt4 book ai didi

java - 如何显示带有字符串计数的字符串

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:26 26 4
gpt4 key购买 nike

我有这样的字符串数组:

String[] str = new String[]{"foo","bar","foo","car"}

我需要这样的输出:

bar1car1foo2

我试过这样的:

String[] someArray = new String[] { "foo","bar","foo","car"};

for(int i=0;i<someArray.length;i++){
int count=0;
for(int j=0;j<someArray.length;j++){
if(someArray[i].equals(someArray[j])){

someArray[i] +=count;
}
}
System.out.println(someArray[i]);
}

我的输出是:

foo0
bar0
foo0
car0

最佳答案

一种选择是使用 Map<String, Integer>其中键代表各个字符串,映射值是每个字符串的计数器。

所以你可以这样做:

Map<String, Integer> stringsWithCount = new TreeMap<>();
for (String item : str) {
if (stringsWithCount.contains(item)) {
stringsWithCount.put(item, stringsWithCount.get(item)+1));
} else {
stringsWithCount.put(item, 0);
}
}

然后您可以在完成后迭代 map :

for (Entry<String, Integer> entry : stringsWithCount.entrySet()) {

并构建您的结果字符串。

这就像老派的实现;如果你想给老师一个惊喜,你可以选择 Java8/lambda/stream 解决方案:

Arrays.stream(str)
.collect(Collectors
.groupingBy(s -> s, TreeMap::new, Collectors.counting()))
.entrySet()
.stream()
.flatMap(e -> Stream.of(e.getKey(), String.valueOf(e.getValue())))
.collect(Collectors.joining())

当然,您应该能够解释那段代码。

关于java - 如何显示带有字符串计数的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39177514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com