切换字母大小写

题目如下

  • 切换字母大小写。如输入字符串 12aBc34,输出字符串 12AbC34

思路如下

  • 正则表达式
  • 通过ASCII码来判断
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* @description 切换字母大小写
* @author sola-grj
*/

/**
* 切换字母大小写(正则表达式)
* @param s str
*/
export function switchLetterCase1(s: string): string {
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
*/
export function switchLetterCase2(s: string): string {
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
}

// // 功能测试
// const str = '100aBcD$#xYz'
// console.info(switchLetterCase2(str))

// // 性能测试
// const str = '100aBcD$#xYz100aBcD$#xYz100aBcD$#xYz100aBcD$#xYz100aBcD$#xYz100aBcD$#xYz'
// console.time('switchLetterCase1')
// for (let i = 0; i < 10 * 10000; i++) {
// switchLetterCase1(str)
// }
// console.timeEnd('switchLetterCase1') // 436ms

// console.time('switchLetterCase2')
// for (let i = 0; i < 10 * 10000; i++) {
// switchLetterCase2(str)
// }
// console.timeEnd('switchLetterCase2') // 210ms

单元测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* @description 切换字母大小写 test
* @author sola-grj
*/

import { switchLetterCase1, switchLetterCase2 } from './switch-letter-case'

describe('切换字母大小写', () => {
it('正常', () => {
const str = '100aBcD$#xYz'
const res = switchLetterCase2(str)
expect(res).toBe('100AbCd$#XyZ')
})
it('空字符串', () => {
const res = switchLetterCase2('')
expect(res).toBe('')
})
it('非字母', () => {
const res = switchLetterCase2('100$%你好')
expect(res).toBe('100$%你好')x
})
})