获取字符串的长度

11/25/2021 简单算法

# 获取字符串的长度

  • 描述 如果第二个参数 bUnicode255For1 === true,则所有字符长度为 1 否则如果字符 Unicode 编码 > 255 则长度为 2 题目链接 (opens new window)

  • 示例

输入: 'hello world, 牛客', false

输出:17
1
2
3

# 自己实现

function strLength(s, bUnicode255For1) {
    if (bUnicode255For1) return s.length
    let result = 0
    for (let i = 0; i < s.length; i++) {
        if (s[i].charCodeAt() > 255) {
            result += 2
        } else {
            result += 1
        }
    }
    return result
}
1
2
3
4
5
6
7
8
9
10
11
12

# 讨论中别人比较好的实现

方法一:通过数组的 reduce 方法累加

function strLength(s, bUnicode255For1) {
    if (bUnicode255For1) return s.length
    return [].reduce.call(
        s,
        function(sum, value) {
            return value.charCodeAt(0) > 255 ? sum + 2 : sum + 1
        },
        0
    )
}
1
2
3
4
5
6
7
8
9
10

方法二:通过正则实现

function strLength(s, bUnicode255For1) {
    return bUnicode255For1 ? s.length : s.length + s.replace(/[\u0000-\u0255]/g, '').length
}
1
2
3
上次更新: 11/25/2021, 6:16:35 PM