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;
}