18. 切换字母大小写

239 阅读1分钟

切换字母大小写

将输入的字符串中小写字母转为大写字母, 大写字母转为小写字母

思路1 正则

/**
 * 正则表达式
 * @param s str
 */

function switchLaterCase (s: string): string {
  const length = s.length
  if (length === 0) return s
  const reg1 = /[a-z]/;
  const reg2 = /[A-Z]/;
  let res: string = ""
  for (let i=0;i<length;i++) {
    let cs = s[i];
    if (reg1.test(cs)) {
      res += cs.toUpperCase()
    }else if (reg2.test(cs)) {
      res += cs.toLowerCase()
    }else {
      res += cs
    }
  }
  return res
}

思路2 ascll

/**
 * ascll
 * @param s str
 */

 function switchLaterCase2 (s: string): string {
  const length = s.length
  if (length === 0) return s
  let res: string = ""
  for (let i=0;i<length;i++) {
    let cs = s[i];
    let n = cs.charCodeAt(0)
    if (n>=97 && n<=122) {
      res += cs.toUpperCase()
    }else if (n>=65 && n <=90) {
      res += cs.toLowerCase()
    }else {
      res += cs
    }
  }
  return res
}

性能测试

正则的速度要比较慢点。