You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++文本转摩尔斯电码输出含首尾多余斜杠,如何修复?

问题原因
  • 现有word2Morse函数的逻辑是每转换一个字符,就无条件追加一个/,直接导致两个错误:
    1. 单词的最后一个字符转换完成后,末尾多了多余的/
    2. 遇到输入里的空格时,空格对应的摩尔斯空格后也会加/,导致单词之间的空格前后出现多余的/
  • 另外数组长度不匹配:morse数组长度为28,letters数组长度为27,遍历会存在数组越界风险。
修复方案

调整转换逻辑:先按空格拆分输入为独立单词,每个单词单独转换为摩尔斯(字符间用/拼接,无首尾多余/),最后把所有单词的转换结果用空格拼接即可。
修改后的代码如下:

// Morse alphabet array 移除morse里的空格,单词分隔单独处理
String morse[26] = {
  ".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---",
  "-.-", ".-..", "--", "-.", "---", ".--.", "--.-", ".-.", "...", "-",
  "..-", "...-", ".--", "-..-", "-.--", "--.."
};
// Alphabet array 移除letters里的空格
char letters[26] = {
  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
  'u', 'v', 'w', 'x', 'y', 'z'
};

// 单个字符转摩尔斯
String char2Morse(char a) {
  int b = tolower(a);
  for (int index = 0; index < 26; index ++) {
    if (b == letters[index]) {
      return morse[index];
    }
  }
  // 非字母字符可按需调整返回值
  return "";
}

// 单个单词转摩尔斯,无首尾多余/
String singleWord2Morse(String word) {
  String res = "";
  for (int i = 0; i < word.length(); i++) {
    res += char2Morse(word[i]);
    // 仅非末尾字符追加/
    if (i != word.length() - 1) {
      res += "/";
    }
  }
  return res;
}

// 整句转摩尔斯入口函数
String text2Morse(String text) {
  String fullRes = "";
  int start = 0;
  int spacePos = text.indexOf(' ');
  // 按空格拆分所有单词
  while (spacePos != -1) {
    String word = text.substring(start, spacePos);
    if (word.length() > 0) { // 跳过连续空格
      if (fullRes.length() > 0) {
        fullRes += " ";
      }
      fullRes += singleWord2Morse(word);
    }
    start = spacePos + 1;
    spacePos = text.indexOf(' ', start);
  }
  // 处理最后一个单词
  String lastWord = text.substring(start);
  if (lastWord.length() > 0) {
    if (fullRes.length() > 0) {
      fullRes += " ";
    }
    fullRes += singleWord2Morse(lastWord);
  }
  return fullRes;
}
测试效果

输入"sos sos",调用text2Morse返回结果为".../---/... .../---/...",完全符合要求。

内容的提问来源于stack exchange,提问作者chazser22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:27:03