提问背景
我一直致力于开发能够读取字符串的代码,压缩它并以压缩形式将其发送到新文件。 (例如"你好,你好" - >"你好[0,1])这个目前很有用。以下是任何想要使用它的人的链接:https://pastebin.com/v6YF34mU。下一阶段是能够使用索引和单词重新创建文件。
问题
我目前有这段代码:
public static void main(String[] args) {
// TODO code application logic here
Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
Matcher seaMatcher = seaPattern.matcher(compressedSea);
while (seaMatcher.find()) {
String seaWords = seaMatcher.group(1);
String[] seaIndexes = seaMatcher.group(2).split(", ");
for (String str : seaIndexes) {
int seaIndex = Integer.parseInt(str);
System.out.print(seaIndex);
}
简而言之。我读取字符串并将其拆分为不同的数组。其中一个数组包含索引,另一个包含单词。下一步是将这些放在一起并创建一个可以压缩的字符串。我对Java比较陌生,所以我不确定如何做到这一点。
如果有人对如何做到这一点有任何想法,我将不胜感激!
答案 0 :(得分:0)
您是否只是问如何将两个字符串放入一个字符串中?或者我理解错了? 如果它只是添加两个字符串,可以使用+符号来完成。
String newString = string1 + string2;
如果你问如何将它们放入一个hashmap(所以键值对),那就是:
HashMap<Integer, String> map = new HashMap<>();
map.put(value, word);
答案 1 :(得分:0)
如果我理解正确的话。
在索引数组中创建索引最高的新数组。
String[] finalString = new Array[highestIndex];
现在遍历你的单词数组
for(String str: wordsArray){
//grab the index of each str
//put your str in the new array at the same indexes
finalString [index] = str;
}
}
答案 2 :(得分:0)
我建议你创建一个用于组合单词和索引的类。
我在下面发布了一条建议:
在OP澄清了他想要输出的内容后更新了答案
public static void main(String[] args) throws FileNotFoundException {
Map<Integer, String> wordMap = new HashMap<Integer, String>();
Pattern seaPattern = Pattern.compile("(.*?)\\[(.*?)\\],");
String compressedSea = "see[2, 4, 5],sea[0, 1, 3],";
Matcher seaMatcher = seaPattern.matcher(compressedSea);
while (seaMatcher.find()) {
String word = seaMatcher.group(1);
String[] seaIndexes= seaMatcher.group(2).split(", ");
for(String s : seaIndexes){
wordMap.put(Integer.valueOf(s), word);
}
}
//HashMap will printout ordered by the key value.
//This is because the key is an Integer
//The hashed key value is therefore the key value itself.
System.out.println(wordMap);
}
<强>输出强>
{0=sea, 1=sea, 2=see, 3=sea, 4=see, 5=see}
<强>加成强>
如果要迭代HashMap,可以执行以下操作:
Iterator it = wordMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getValue());
}
<强>输出强>
sea
sea
see
sea
see
see