gpt4 book ai didi

java - 如何返回二维字符串

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:06:02 25 4
gpt4 key购买 nike

我不完全明白如何返回二维对象。所以我写了一个方法,它接受一个文档的输入,我必须返回其中所有唯一单词及其出现次数的列表,按出现次数降序排列。这是一个要求,我无法控制它作为 String 的二维数组返回。

到目前为止,这是我所拥有的:

static String[][] wordCountEngine(String document) {
// your code goes here
if (document == null || document.length() == 0)
return null;

Map<String, String> map = new HashMap<>();
String[] allWords = document.toLowerCase().split("[^a-zA-Z]+");

for (String s : allWords) {
if (map.containsKey(s)) {

int newVersion = (Integer.parseInt(map.get(s).substring(1, map.get(s).length())) + 1);
String sb = Integer.toString(newVersion);
map.put(s, sb);
} else {
map.put(s, "1");
}
}

String[][] array = new String[map.size()][2];
int count = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
array[count][0] = entry.getKey();
array[count][1] = entry.getValue();
count++;
}

return array;
}

我正在尝试使用 HashMap 来存储单词及其出现次数。将表中的键 --> 值对存储到 String[][] 中的最佳方法是什么?如果输入是:

input:  document = "Practice makes perfect. you'll only
get Perfect by practice. just practice!"

输出应该是:

output: [ ["practice", "3"], ["perfect", "2"],
["by", "1"], ["get", "1"], ["just", "1"],
["makes", "1"], ["only", "1"], ["youll", "1"] ]

如何在二维数组中存储这样的数据?

最佳答案

String[][]只是这个任务的数据结构是错误的。你应该使用 Map<String, Integer> map而不是 <String, String>在方法运行期间,只需准确返回该映射。

这有多种原因:

  • 整数存储为字符串,甚至通过再次将字符串解析为整数来进行计算,计算然后再解析回来 - 坏主意。
  • 返回的数组不保证维度,没有办法强制每个子数组恰好有两个元素。

关于您的评论的注意事项:如果(出于某种原因)您需要将 map 转换为 String[][]您当然可以这样做,但是转换逻辑应该与生成 map 本身的代码分开。这样 wordCountEngine 的代码保持清洁且易于维护。

关于java - 如何返回二维字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48024802/

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