Reputation: 1636
Task is to check whether string results true or false for following given condition:
If a letter a to z occurs it must have '+' before and after the particular letter This works fine expect the case when '=' comes before or after the letter. Why this condition is wrong for '=' ? This code returns true for these strings Thanks
function SimpleSymbols(str) {
var temp=str.split("")
if(temp.length==1 || temp.length==2 )
return false;
for(i=0;i<temp.length;i++){
if(temp[i]>='a' && temp[i]<='z'){
if(i===0 || i===(temp.length-1)||
(temp[i-1]!=='+' && temp[i+1]!=='+')){
return false;
}
}
}
return true;
}
Upvotes: 0
Views: 67
Reputation: 4021
The condition (temp[i-1]!=='+' && temp[i+1]!=='+')
is only true if both the character before and after the letter are not pluses. If one of them is a plus sign the condition is false.
You need to change the logical and to an or operator: (temp[i-1]!=='+' || temp[i+1]!=='+')
The original condition is that a letter is surrounded by plus signs:
temp[i-1] === '+' && temp[i+1] === '+'
In your if
clause you test that this condition is not matched. So, the original condition becomes:
!(temp[i-1] === '+' && temp[i+1] === '+')
To transform this into a condition using not-equals, you need to apply De Morgan's Laws which basically say that a logical and becomes an or and vice-versa if you factor in a negation. This makes the resulting condition:
temp[i-1] !== '+' || temp[i+1] !== '+'
Upvotes: 2
Reputation:
Hint: check out these strings too, they all return true even though they should return false.
"+a4"
"1a+"
"%a+"
Let's simplify your condition:
str[i-1] !== '+' && str[i+1] !== '+'
is the same as
!(str[i-1] === '+' || str[i+1] === '+')
This makes it easier to see what you were really checking.
We can see now that the condition str[i-1] !== '+' && str[i+1] !== '+'
returns true only if neither of those two characters are a +
.
You want it to return true if at least one is not a +
. So you should use this instead:
str[i-1] !== '+' || str[i+1] !== '+'
I re-wrote your code with this correct condition here:
function SimpleSymbols(str) {
if (str.length == 1 || str.length == 2) return false;
for (var i = 0; i < str.length; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
if (i === 0 || i === (str.length-1) || (str[i-1] !== '+' || str[i+1] !== '+')) {
return false;
}
}
}
return true;
}
Note: regular expressions can help out a lot with pattern-matching in strings like this.
E.g. your whole function would have simply become the regex:
function SimpleSymbols(str) {
return !str.match(/[^+][a-z][^+]/) && str.length > 2;
}
Upvotes: 1
Reputation: 473
<!-- I think you should change the condition operator -->
function SimpleSymbols(str) {
var temp=str.split("")
if(temp.length==1 || temp.length==2 )
return false;
for(i=0;i<temp.length;i++){
if(temp[i]>='a' && temp[i]<='z'){
if(i===0 || i===(temp.length-1)||
(temp[i-1]!=='+' || temp[i+1]!=='+')){
return false;
}
}
}
return true;
}
Upvotes: 2