切换字母大小写

202 阅读1分钟

切换字母大小写

题目

切换字母大小写,输入 'aBc' 输出 'AbC'

分析

需要判断字母是大写还是小写

  • 正则表达式
  • charCodeAt 获取 ASCII 码(ASCII 码表,可以网上搜索)

性能分析

  • 正则表达式性能较差
  • ASCII 码性能较好
/**
 * 切换字母大小写(正则表达式)
 * @param s str
 */
function switchLetterCase1(s) {
  let res = '';

  const length = s.length;
  if (length === 0) return res;

  const reg1 = /[a-z]/;
  const reg2 = /[A-Z]/;

  for (let i = 0; i < length; i++) {
    const c = s[i];
    if (reg1.test(c)) {
      res += c.toUpperCase();
    } else if (reg2.test(c)) {
      res += c.toLowerCase();
    } else {
      res += c;
    }
  }

  return res;
}

/**
 * 切换字母大小写(ASCII 编码)
 * @param s str
 */
function switchLetterCase2(s) {
  let res = '';

  const length = s.length;
  if (length === 0) return res;

  for (let i = 0; i < length; i++) {
    const c = s[i];
    const code = c.charCodeAt(0);

    if (code >= 65 && code <= 90) {
      res += c.toLowerCase();
    } else if (code >= 97 && code <= 122) {
      res += c.toUpperCase();
    } else {
      res += c;
    }
  }

  return res;
}