Explain work of lastIndexOf in this for loop [duplicate] - javascript

This question already has answers here:
confusion about lastIndexOf in javascript
(3 answers)
Closed 8 months ago.
Can somebody explain to me how exactly lastIndexOf works here?
To be specific: I do not understand how comparing str[i] !== i works here. How does it detect if the character is repeating?
This had to be a simple exercise to find if str has unique characters that are not going twice in the same str.
isUnique('abcdef'),
isUnique('89%df#$^a&'),
isUnique('abcaef'));
function isUnique(str)
{
for(var i = 0; i < str.length; i++)
{
if(str.lastIndexOf(str[i]) !== i) return false;
}
return true;
}

assume you have a string like this: 'abcaef', let's start and check that if it is unique or not...
we start from first char: 0 and str[0] is a and if all chars in str are unique, we expect that lastIndexOf("a") return 0 but it return 3 and it means there is another a that it is not in position 0
note that lastIndexOf return index from left, but it check from right and return index of first occurrence from right:
a b c a e f
0 1 2 3 4 5 <-

Related

Find if the sentence has 3 consecutive words

You are given a string with words and numbers separated by whitespaces (one space). The words contains only letters. You should check if the string contains three words in succession. For example, the string "start 5 one two three 7 end" contains three words in succession.
Input : String
Output : Boolean
This is what I'm trying to do, please point out my mistake. Thanks.
function threeWords(text){
let lst = text.split(' ');
for (let i=0; i< 3; i++) {
if (typeof lst[i] === 'string' && Number(lst[i]) === NaN) {return true}
else {return false;}}
}
If you'd rather continue with your code than use regex, here are your issues:
You only loop over 3 of the elements in lst. Loop over the entire length of the list.
You try to check if Number('somestring') === NaN. In JavaScript, NaN === NaN is False. Use isNaN() instead.
Once you find a list element that is not a number, you return True. You should have a variable that keeps track of how many words there are in succession (resetting to 0 when you find a number), and return True when this variable is equal to 3.
Here is the fixed code:
function threeWords(text) {
let lst = text.split(' ');
let num_words = 0;
for (let i = 0; i < lst.length; i++) {
if (isNaN(Number(lst[i])))
num_words++
else
num_words = 0
if (num_words === 3)
return true
}
return false;
}
Might be easier with a regular expression:
const result = /([A-Za-z]+( |$)){3}/.test('start 5 one two three 7 end');
console.log(result);

Bean Counting WITHOUT using for loop and regex [duplicate]

This question already has answers here:
How to count string occurrence in string?
(40 answers)
Closed 2 years ago.
I tried to solve the following problem without using the for loop:
"Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
console.log(countBs("BBC")); // → 2
Thank you for your help.
Here is the code I wrote so far which doesn't work:
function countBs(word) {
let count = 0
if (word.length == 0) {
return count;
} else {
if (word[word.length - 1] == 'B') {
count++
}
return countBs(word.slice(0, word.length - 1))
}
}
console.log(countBs("BBC"))
You can easily use regex for this case:
function countBs(word) {
const matches = word.match(/B/g);
return matches && matches.length || 0;
}
Basically it globally searches for occurrences of 'B'. If it find it, it returns the length of it, if the matches are null it will return 0.
Simpler less expressive:
function countBs(word) {
return (word.match(/B/g) || []).length;
}

String of numbers can't start with zero. Other Solutions? [duplicate]

This question already has answers here:
Remove leading zeros from a number in Javascript [duplicate]
(3 answers)
Closed 5 years ago.
I have a string that only contains numbers, but the string can not start with a zero.
The first thing I cam up with was this:
let myNumber = "0052";
myNumber = myNumber.split('');
for (let i = 0; i < myNumber.length; i++) {
if (myNumber[i] == '0') {
myNumber.splice(i, 1);
i--;
} else {
break;
}
}
console.log(myNumber);
console.log('result:', myNumber.join(''));
Everything works fine like that.
I thought there might be an other way without using a classical for-loop.
My attempt with a for-of loop failed. As soon as I remove the first entry of my array, the index of the loop does not reset, so it skips the second zero in my array. Here is the code for that:
let myNumber = "0052";
myNumber = myNumber.split('');
for (let n of myNumber) {
if (n == '0') {
myNumber.shift();
} else {
break;
}
}
console.log(myNumber);
console.log('result:', myNumber.join(''));
What other solutions to this problem are there? Is there a more performant solution?
What you're probably looking for is parseInt function.
const result = parseInt("0052", 10).toString();
console.log(result);
I also added toString() to convert number to a string. parseInt also accepts second argument - the radix. Read more about parseInt
Regexp: /^[0]+/
let myNumber = "0000000520";
console.log(myNumber.replace(/^[0]+/, ''))
Use
parseInt('0052') = 52
or
parseFloat('0052.29') = 52.29 if your number is float type:
I just have different and simpler approach than yours :)
while(myNumber.length){
if(myNumber.charAt(0) == '0')
myNumber = myNumber.substring(1, myNumber.length);
}
DEMO : https://jsbin.com/falejuruwu/1/edit?js,console

Check a string that MUST contain another string [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I want to check if string b is completely contained in string a.
I tried:
var a = "helloworld";
var b = "wold";
if(a.indexOf(b)) {
document.write('yes');
} else {
document.write('no');
}
The output is yes, it is not my expected output, because string b(wold) is not completely contained in string a(helloworld) --- wold v.s. world
Any suggestion to check the string?
Read the documentation: MDC String.indexOf :)
indexOf returns the index the match was found. This may be 0 (which means "found at the beginning of string") and 0 is a falsy value.
indexOf will return -1 if the needle was not found (and -1 is a truthy value). Thus the logic on the test needs to be adjusted to work using these return codes. String found (at beginning or elsewhere): index >= 0 or index > -1 or index != -1; String not found: index < 0 or index == -1.
Happy coding.
You need to use if(a.indexOf(b) > -1) instead. indexOf returns -1 when it can't find a string.
.indexOf returns -1 if no match was found, which is a truthy value. You'll need to check more explicitly:
if (a.indexOf(b) != -1)
That's because indexOf returns -1 if a value is not found:
if(a.indexOf(b) != -1) {
you may want to use this
if(a.indexOf(b) != -1)
You need to test if the result is -1. -1 indicates no match, but evaluates to true in a boolean sense.
var a = "helloworld";
var b = "wold";
if(a.indexOf(b) > -1) {
document.write('yes');
} else {
document.write('no');
}

Optimum way to compare strings in JavaScript? [duplicate]

This question already has answers here:
Is there a JavaScript strcmp()?
(7 answers)
Closed 9 years ago.
The community reviewed whether to reopen this question last month and left it closed:
Original close reason(s) were not resolved
I am trying to optimize a function which does binary search of strings in JavaScript.
Binary search requires you to know whether the key is == the pivot or < the pivot.
But this requires two string comparisons in JavaScript, unlike in C like languages which have the strcmp() function that returns three values (-1, 0, +1) for (less than, equal, greater than).
Is there such a native function in JavaScript, that can return a ternary value so that just one comparison is required in each iteration of the binary search?
You can use the localeCompare() method.
string_a.localeCompare(string_b);
/* Expected Returns:
0: exact match
-1: string_a < string_b
1: string_a > string_b
*/
Further Reading:
MDN: String.prototype.localeCompare
Stack Overflow - Is there a JavaScript strcmp()?
Tutorials Point: JavaScript String - localeCompare() Method
Well in JavaScript you can check two strings for values same as integers so yo can do this:
"A" < "B"
"A" == "B"
"A" > "B"
And therefore you can make your own function that checks strings the same way as the strcmp().
So this would be the function that does the same:
function strcmp(a, b)
{
return (a<b?-1:(a>b?1:0));
}
You can use the comparison operators to compare strings. A strcmp function could be defined like this:
function strcmp(a, b) {
if (a.toString() < b.toString()) return -1;
if (a.toString() > b.toString()) return 1;
return 0;
}
Edit    Here’s a string comparison function that takes at most min { length(a), length(b) } comparisons to tell how two strings relate to each other:
function strcmp(a, b) {
a = a.toString(), b = b.toString();
for (var i=0,n=Math.max(a.length, b.length); i<n && a.charAt(i) === b.charAt(i); ++i);
if (i === n) return 0;
return a.charAt(i) > b.charAt(i) ? -1 : 1;
}

Categories

Resources