zoukankan      html  css  js  c++  java
  • 获取字符串的长度

    题目描述

    编写function strLength(s, bUnicode255For1) {};

    如果第二个参数 bUnicode255For1 === true,则所有字符长度为 1
    否则如果字符 Unicode 编码 > 255 则长度为 2
    输入例子:
    strLength('hello world, 牛客', false)
    输出例子:
    17

    题目解析

    JavaScript charCodeAt(index) 方法

    定义和用法

    charCodeAt() 方法可返回指定位置的字符的 Unicode 编码。这个返回值是 0 - 65535 之间的整数。

    方法 charCodeAt() 与 charAt() 方法执行的操作相似,只不过前者返回的是位于指定位置的字符的编码,而后者返回的是字符子串。

    语法: stringObject.charCodeAt(index)
    注释:字符串中第一个字符的下标是 0。如果 index 是负数,或大于等于字符串的长度,则 charCodeAt() 返回 NaN。


    示例代码1
     1 function strLength(s, bUnicode255For1) {
     2         function strLength(s, bUnicode255For1) {
     3             if(bUnicode255For1 === true){
     4                 return s.length;               
     5             }
     6  
     7             var length=0;
     8             for(var i=0, len=s.length; i<len; i++){
     9                 if(s.charCodeAt(i)>255)
    10                     length+=2;
    11                 else
    12                     length+=1;
    13             }
    14             return length;
    15         }
    16         //console.log(strLength('hello world, 牛客', false));   
    17 }

        遍历字符串中的每一个字符,如果字符Unicode 编码 > 255,则长度加2,否则加1,直至遍历完所有字符,最后返回字符串长度。

    示例代码2

     1 function strLength(s, bUnicode255For1) {
     2     if(bUnicode255For1 === true){
     3         return s.length;                
     4     }
     5 
     6     for(var i=0,m=0,len=s.length; i<len; i++){
     7         if(s.charCodeAt(i)>255)
     8             m++;
     9     }
    10     return m*2+(s.length-m);  
    11 }
    12 //console.log(strLength('hello world, 牛客', false));

      遍历字符串中的字符,统计Unicode 编码 > 255字符的个数m,最后根据 m+s.length返回字符串长度。

    参考链接

    链接:https://www.nowcoder.com/questionTerminal/e436bbc408744b73b69a8925fac26efc
    来源:牛客网

  • 相关阅读:
    js将url转换二维码
    百度地图api使用
    js字符串转日期兼容性
    Object.keys的使用
    Web App和Native App的比较
    数组转为对象
    常用meta整理
    git merge和git rebase的区别
    GitHub 翻译之 'Hello-world' 翻译
    js数据类型
  • 原文地址:https://www.cnblogs.com/guorange/p/6604627.html
Copyright © 2011-2022 走看看