Click here to Skip to main content
15,883,603 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a doubt on an assignment of which I have the answer. The answer is little bit different from the code I've tried, so I'd like to clarify this doubt.

The statement is the following:

Make a function that receives a string as a parameter, mixing letters and numbers, and returns a string containing only letters of the past string at the same order.

Example: if the input is "ab2c4d", the function must return "abcd".

Example: if the input is "1234", the function must return "".

The correct answer is:

JavaScript
function removesNumbers(string) {

    let newstring = "";
   
    for (let i = 0; i<string.length; i++){
      if (string[i] != "0" && string[i] != "1" && string[i] != "2" && string[i] != "3" && string[i] != "4" && string[i] != "5" && string[i] != "6" && string[i] != "7" && string[i] != "8" &&  string[i] != "9"){

        newstring = newstring + string[i];      
    }        
}
      return newstring;  
}


The code I've tried is almost the same, the only difference is that in the "if" statemente, instead of using &&, I used || and didn't get the correct output.

Could someone please explain why using || is the wrong way to go?

Thanks.

What I have tried:

JavaScript
function removesNumbers(string) {

    let newstring = "";
   
    for (let i = 0; i<string.length; i++){
      if (string[i] != "0" || string[i] != "1" || string[i] != "2" || string[i] != "3" || string[i] != "4" || string[i] != "5" || string[i] != "6" || string[i] != "7" || string[i] != "8" ||  string[i] != "9"){

        newstring = newstring + string[i];      
    }        
}
      return newstring;  
}
Posted
Updated 24-Jan-23 19:31pm
v2

&& and || are different operations: a && b is an AND operation, which is true only if a and b are both true. If either or both are false, the result is false as well.

a || b is an OR operation, which is true if either or both a and b are true. Only if both are false is the result false as well.

So when you say if (string[i] != "0" || string[i] != "1" || ...It is always true, because string[i] cannot be both "0" and "1" at the same time.
 
Share this answer
 
v2
The hex value of of '9' is 0x39 and everything above it is either a character or special character. i.e. ';:<=>?@' why not do;
Assuming you're not worried about special characters, as it seem you're not;
C++
if (string[i] >= 0x30) 
    newstring = newstring + string[i];  
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900