I am working on a practice problem:
Return the length of a string without using javascript's native
string.length
method.
The only ways I could think of would be substring
or slice
, but I'm stumped.
Program to find the length of a string without using the strlen() function is discussed here. Length of a string can be found by scanning the string, character by character until an empty space '/0' is encountered.
You can loop over the string, testing to see whether there is a non-undefined
value at each index (as soon as you get an undefined
value you've run past the end of the string):
function strLength(s) {
var length = 0;
while (s[length] !== undefined)
length++;
return length;
}
console.log(strLength("Hello")); // 5
console.log(strLength("")); // 0
(I'm assuming that if you're not allowed to use the native string .length
property that you probably shouldn't use the array .length
property either with str.split("").length
...)
Given that this is a practice problem, I suspect the OP may not want ES6/ES2015, but, just in case that's an option, and/or for whoever else is looking at this, here's a concise modern approach:
const str = "Hello world!";
console.log([...str].reduce(a => a+1, 0));
(When I posted this, no other answer had proposed this solution. However, I had missed the fact that @MarkoGrešak had essentially proposed this exact solution in a comment to another question.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With