Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I try to compare a split up string with multiple characters

Tags:

javascript

var input = 'HISFANTOR';
var output = [];
var char = input.split('');

for (var i = 0, len = char.length; i < len; i++) {
   if (char[i] == 'H' || 'K' || 'Y' || 'V' || 'B' || 'C' || 'N' || 'O' || 'F' || 'P' || 'S' || 'I' || 'U'){
      output.push(char[i]);
   }else{
      output.push('0');
   }
}
console.log(output);

I had it with cases first and it worked but looked way too much so I thought I try or but I get an output of the input

what I expect is this:

["H", "I", "S", "F", "0", "N", "0", "O", "0"]
like image 299
Hisfantor Avatar asked Mar 05 '19 18:03

Hisfantor


People also ask

How do I split a string into multiple characters?

To split a String with multiple characters as delimiters in C#, call Split() on the string instance and pass the delimiter characters array as argument to this method. The method returns a String array with the splits. Reference to C# String. Split() method.

How do you compare string elements with characters?

strcmp() in C/C++ This function is used to compare the string arguments. It compares strings lexicographically which means it compares both the strings character by character. It starts comparing the very first character of strings until the characters of both strings are equal or NULL character is found.

Can you split by multiple characters in Python?

split() This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.

How do you compare parts of a string?

compare() is a public member function of string class. It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. The compare() can process more than one argument for each string so that one can specify a substring by its index and by its length.


1 Answers

The pattern

char[i] == 'H' || 'K' || 'Y'

returns the first truthy value, which is the comparison with 'H' or if the comparison is false, it takes 'K'. All other strings are not used.

For taking a check if the character is in an array or a string, you could use includes (Array#includes/String#includes) which checks a given value against an array or string and returns true or false.

This proposal uses Array.from which takes a string, (basically any iterables, or an object with a length property) and returns an array of characters. An while this method contains a mapping functionality, you could check the character and return a differetn character, based on the check.

var input = 'HISFANTOR',
    output = Array.from(input, c => 'HKYVBCNOFPSIU'.includes(c) ? c : 0);

console.log(...output);
like image 176
Nina Scholz Avatar answered Sep 24 '22 01:09

Nina Scholz