虽然都是很简单的算法,每一个都只需5分钟左右,但写起来总会遇到不一样的小问题,但愿你们能跟我一块儿天天进步一点点。
更多的小算法练习,能够查看个人文章。javascript
Using the JavaScript language, have the function LetterChanges(str)
take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string. java
使用JavaScript语言,使用函数LetterChanges(str)
获取传递的str参数并使用如下算法对其进行修改。
将字符串中的每一个字母替换为字母表后面的字母(即 c变为d,z变为a)。
而后将这个新字符串(a,e,i,o,u)中的每一个元音大写,并最终返回此修改后的字符串。算法
Input:"hello*3" Output:"Ifmmp*3" Input:"fun times!" Output:"gvO Ujnft!" Input:"I love Code Z!" Output:"J mpwf DpEf A!"
function LetterChanges(str) { var strArr = ['a', 'e', 'i', 'o', 'u'] var newStr = '' for(var i=0;i<str.length;i++) { var asciiCode = str[i].charCodeAt(0) var tempStr = str[i] if (asciiCode <= 122 && asciiCode >= 97) { asciiCode = asciiCode === 122 ? 97 : asciiCode + 1 tempStr = String.fromCharCode(asciiCode) }else if(asciiCode <= 90 && asciiCode >= 65) { asciiCode = asciiCode === 90 ? 65 : asciiCode + 1 tempStr = String.fromCharCode(asciiCode) } if(strArr.indexOf(tempStr) !== -1) { tempStr = tempStr.toUpperCase() } newStr += tempStr } return newStr; }
function LetterChanges(str) { str = str.replace(/[a-zA-Z]/g, function(ch) { if (ch === 'z') return 'a'; else if (ch === 'Z') return 'A'; else return String.fromCharCode(ch.charCodeAt(0) + 1); }); return str.replace(/[aeiou]/g, function(ch) { return ch.toUpperCase(); }); }
方法1: 使用ASCII码去判断,a-z(97,122)之间;A-Z(65,90)之间api
方法2:使用正则去匹配,特殊状况如"z"和"Z",返回对应的值函数
charCodeAt()
,获取字符串的ASCII码String.fromCharCode()
, 把ASCII码转换成字符串