In a factory a printer prints labels for boxes. For one kind of boxes the printer has to use colors which, for the sake of simplicity, are named with letters from a to m
.
The colors used by the printer are recorded in a control string. For example a "good" control string would be aaabbbbhaijjjm
meaning that the printer used three times color a, four times color b, one time color h then one time color a...
Sometimes there are problems: lack of colors, technical malfunction and a "bad" control string is produced e.g. aaaxbbbbyyhwawiwjjjwwm
with letters not from a to m
.
You have to write a function printer_error
which given a string will output the error rate of the printer as a string representing a rational whose numerator is the number of errors and the denominator the length of the control string. Don't reduce this fraction to a simpler expression.
The string has a length greater or equal to one and contains only letters from a
to z
.
#Examples:
s="aaabbbbhaijjjm"
error_printer(s) => "0/14"
s="aaaxbbbbyyhwawiwjjjwwm"
error_printer(s) => "8/22"
意思大概就是计算给定字符串中n-z的字母数量a,和字符串长度b,返回 a/b---->这里是一个字符串
我的代码:
function printerError(s) {
// your code
if(s==null){
return error;
}else{
if (s.match(/[^a-m]/gi)==null){
var err = 0;
}else {
var err = s.match(/[^a-m]/gi).length
}
var len = s.length;
var res = err + '/' + len;
return res;
}
}
说一下问题,经过这两天的做题,我很自然的想到可以用正则,但是还有一个问题就是 match()方法的使用问题。。。match()最后生成的一个数组,看一下match()的文档,
如果没有匹配到的就返回null,当求null的长度时就会报错,Cannot read property 'length' of null,
这个错误基本就是没有这个属性,一般都是数据类型的问题
所以要加一个判定。
看了别人的写法,真的是自叹不如:
function printerError(s) {
return `${s.replace(/[a-m]/ig, '').length}/${s.length}`;
}
replace()返回的是字符串,空字符串的长度为0,就不会存在前面的问题
function printerError(s) {
return (s.match(/[n-z]/ig) === null ? 0 : s.match(/[n-z]/ig).length) + '/' + s.length ;
}
使用?:判断s.match(/[n-z]/ig)是否为空,为空返回0;否则返回s.match(/[n-z]/ig)的长度,,,,