gpt4 book ai didi

java - 拆分字符串,记住分隔符并将其附加为空格

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:46:14 24 4
gpt4 key购买 nike

大家好

我有一个看起来像这样的字符串(摩尔斯电码):

....x.x.-..x.-..x---xx...x-x.-x-.-.x-.-x---x...-x.x.-.x..-.x.-..x---x.--

单“x”表示字母在该点结束,双“x”表示它是整个单词的结尾。我有一张带有摩尔斯电码的 map 。我用“x”拆分字符串,然后将每个编码字母与我的字典中的值进行比较,并将匹配的键附加到我的 StringBuilder,它工作正常,但我想在单词之间保留空格而不是双 xx。

我的一段代码:

private static final Map<Character, String> morseCode;
static {
morseCode = new HashMap<Character, String>();
morseCode.put('h', "....");
morseCode.put('e', ".");
morseCode.put('l', ".-..");
morseCode.put('o', "---");
morseCode.put('s', "...");
morseCode.put('t', "-");
morseCode.put('a', ".-");
morseCode.put('c', "-.-.");
morseCode.put('k', "-.-");
morseCode.put('v', "...-");
morseCode.put('r', ".-.");
morseCode.put('f', "..-.");
morseCode.put('w', ".--");
}

String decodedMorseTable = "....x.x.-..x.-..x---xx...x-x.-x-.-.x-.-x---x...-x.x.-.x..-.x.-..x---x.--"
StringBuilder decodedText = new StringBuilder();
String[] splitLetters = decodedMorseTable.split("x");
for(String letter: splitLetters) {
for(Map.Entry<Character, String> entry: morseCode.entrySet()) {
if(entry.getValue().equals(letter))
decodedText.append(entry.getKey());

输出:

hellostackoverflow

最佳答案

首先尝试将输入拆分为单独的单词(通过 xx)。然后像以前一样拆分每个单词:

String decodedMorseTable = "....x.x.-..x.-..x---xx...x-x.-x-.-.x-.-x---x...-x.x.-.x..-.x.-..x---x.--";
StringBuilder decodedText = new StringBuilder();
String[] words = decodedMorseTable.split("xx");
for (String word : words) {
String[] splitLetters = word.split("x");
for (String letter : splitLetters) {
for (Map.Entry<Character, String> entry : morseCode.entrySet()) {
if (entry.getValue().equals(letter))
decodedText.append(entry.getKey());
}
}
decodedText.append(" ");
}

更新

如果您修改您的 morseCode 以将莫尔斯字母作为键并将字符作为值,那么代码将看起来更简单(避免第三个循环):

private static final Map<String, Character> morseCode;
static {
morseCode = new HashMap<>();
morseCode.put("....", 'h');
morseCode.put(".", 'e');
morseCode.put("", ' ');
...


String[] splitLetters = word.split("x");
for (String letter : splitLetters) {
decodedText.append(morseCode.get(letter));
}

Java 1.8+解决方案:

Arrays.stream(decodedMorseTable.split("x"))
.map(morseCode::get)
.forEach(decodedText::append);

关于java - 拆分字符串,记住分隔符并将其附加为空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53365069/

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