codewars 5kyu Simple Pig Latin

codewars 5kyu Simple Pig Latin

题目大意:把每个单词的第一个字母移到该单词的末尾,最后在单词末尾加上 ay,输出字符串。标点符号不进行处理。

我的思路是先把每个单词以空格为分割存到一个列表里,对列表里每个单词进行处理,如果该词是标点符号,不做处理,否则就把该词的第一个字母移到该词的末尾,最后在单词末尾加上 ay 和空格,如果是最后一个单词,末尾不加空格。

function pigIt(str) {
  //Code here
  var temp = str.split(" ");
  var ans = "";
  for (let i = 0; i < temp.length; i++) {
    if (
      temp[i].charCodeAt() < 65 ||
      (temp[i].charCodeAt() > 90 && temp[i].charCodeAt() < 97) ||
      temp[i].charCodeAt() > 122
    ) {
    } else {
      temp[i] = temp[i].slice(1, temp[i].length) + temp[i][0] + "ay";
    }

    if (i != temp.length - 1) {
      ans += temp[i] + " ";
    } else {
      ans += temp[i];
    }
  }
  return ans;
}

中间也想到用正则表达式,但是正则还不大会用。

function pigIt(str) {
  return str.replace(/(\w)(\w*)(\s|$)/g, "$2$1ay$3");
}
const pigIt = (s) => s.replace(/(\w)(\w*)/g, "$2$1ay");
function pigIt(str) {
  return str.replace(/\w+/g, (w) => {
    return w.slice(1) + w[0] + "ay";
  });
}
function pigIt(str) {
  var arrayWord = str.split(" ");
  return arrayWord
    .map(function (word) {
      var firstLetter = word.charAt(0);
      return word.slice(1) + firstLetter + "ay";
    })
    .join(" ");
}
function pigIt(str) {
  return str
    .split(" ")
    .map((item) => `${item.substr(1)}${item[0]}ay`)
    .join(" ");
}

也有这样条理清晰代码行数比我多的大佬~

function pigIt(str) {
  let newStr = "";
  const array = str.split(" ");
  for (let i of array) {
    let firstLetter = ""; //use to store the first letter in the word
    for (let j in i) {
      if (j === "0") {
        firstLetter += i[j]; //store first letter
      } else {
        newStr += i[j];
      }
    }
    newStr += firstLetter; //put it into end of the word
    newStr += " "; //space
  }
  newArray = newStr.split(" ");
  newArray.pop(); //delete the empty space
  let result = ""; //store the result
  for (let index of newArray) {
    if (index.length != 1) {
      result += index;
      result += "ay";
      result += " ";
    } else if (index.length == 1) {
      if (index == "?" || index == "!" || index == ".") {
        //use to check if the last length is not equal symbol
        result += index;
      } else {
        result += index;
        result += "ay";
        result += " ";
      }
    }
  }

  if (result[result.length - 1] === " ") {
    //delete last space
    result = result.slice(0, result.length - 1);
  }
  return result;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值