未能通过CamelCase测试

问题描述 投票:0回答:1

我在这个练习中遇到了困难:

给定一个字符串n。任务是以驼峰命名法返回句子。这意味着每个新单词都会大写并立即附加到旧单词之后。以小写字母开头。

我试过这个:

function camelCase(s) {
  let result = "";

  // Convert the first character to lowercase
  result += s[0].toLowerCase();

  for (let i = 1; i < s.length; i++) {
    // Check for spaces and capitalize the next character
    if (s[i] === ' ') {
      result += s[i + 1].toUpperCase();
      i++; // Skip the space character
    } else {
      result += s[i];
    }
  }

  return result;
}

但出现此错误:https://i.stack.imgur.com/duZVr.png

javascript camelcasing
1个回答
0
投票

从注释中可以看到,任何以空字符结尾的字符串都会导致崩溃。

示例:“Hi”会使您的代码崩溃,因为“”后面没有字符可以转换为大写。处理此问题的最简单方法是在崩溃行之前使用一个简单的条件,即:

...
if (s[i] === ' '){
  if (!s[i + 1]) break; // Break since we are at the end of the sentence
  result += s[i + 1].toUpperCase();
...

这会检查末尾是否有字符,如果没有,它就会中断。

© www.soinside.com 2019 - 2024. All rights reserved.