首页 > 试题广场 >

获取字符串的长度

[编程题]获取字符串的长度
  • 热度指数:35174 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
如果第二个参数 bUnicode255For1 === true,则所有字符长度为 1
否则如果字符 Unicode 编码 > 255 则长度为 2

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


输出描述:
17
示例1

输入

'hello world, 牛客', false

输出

17
头像 yyjbfdm
发表于 2020-10-15 23:34:17
function strLength(s, bUnicode255For1) { var length=s.length; if(!bUnicode255For1){ for( var i in 展开全文
头像 我是前你是后
发表于 2021-10-21 11:30:39
简单直观的解题办法 首先:我觉得读懂题目很重要,刚开始我就没怎么读懂 1、它的意思是如果传进来的参数(也就是bUnicode255For1)是传的true, 那么字符串中每个字符按照1的长度来计算 2、如果传进来的是flase,那么再对每一个字符进行判断,如果它们的unicode编码>255( 展开全文
头像 牛客988280338号
发表于 2021-08-11 14:35:07
利用charCodeAt(index)的方法获得字符的ascll码,利用for in获取index,如果大于255的总长度加上1。第二种方法,把字符串转换成字符数组,对数组进行遍历,利用charCodeAt(index)的方法获得字符的ascll码,如果大于255的总长度加上1。
头像 是明啊
发表于 2021-07-28 15:17:11
function strLength(s, bUnicode255For1) { if(bUnicode255For1){ return s.length; } let len = s.length; s.split('').forEach(si =& 展开全文
头像 stone201901172130920
发表于 2021-08-24 10:33:51
感觉牛客网的题很多都很简单,但是描述都太过简洁,第一眼看完总是没看懂题意QAQ function strLength(s, bUnicode255For1) { // 为 true 直接返回 s.length if (bUnicode255For1) { return s.lengt 展开全文
头像 lemon031
发表于 2021-08-12 10:25:33
function strLength(s, bUnicode255For1) { let l = s.length if(!bUnicode255For1) { for(let i in s) { s.charCodeAt(i) > 255 ? l++ : l 展开全文
头像 前端消防圆
发表于 2023-06-21 21:26:29
思路:遍历字符串,使用string.charCodeAt(index)方法获取对应下标处字符的Unicode编码值,返回一个介于0到65535之间的整数,其中大于255的算作两个长度。 function strLength(s, bUnicode255For1) { if(bUnicode 展开全文
头像 忘魂儿
发表于 2021-09-22 22:27:22
function strLength(s, bUnicode255For1) { var total=0 //匹配空格的数目 var space=s.match(/ /g) var spaceLength=0 for (i in space){ 展开全文
头像 牛客574740459号
发表于 2023-04-10 11:04:04
function strLength(s, bUnicode255For1) { if (bUnicode255For1) { return s.length; } var len = 0; for (let i = 0; i < s.length; i++) { 展开全文
头像 优秀的阿二
发表于 2023-07-21 14:59:18
function strLength(s, bUnicode255For1) { if(bUnicode255For1){return s.length} let count =0; s.split('').forEach(i 展开全文