在 JavaScript 中將字串交換為二進位制字串
我們需要編寫一個 JavaScript 函式,其中包含一個小寫字串,並返回一個新字串,其中 [a, m] 之間的全部元素都表示為 0,而 [n, z] 之間的全部元素都表示為 1。
示例
其程式碼如下 −
const str = 'Hello worlld how are you';
const stringToBinary = (str = '') => {
const s = str.toLowerCase();
let res = '';
for(let i = 0; i < s.length; i++){
// for special characters
if(s[i].toLowerCase() === s[i].toUpperCase()){
res += s[i];
continue;
};
if(s[i] > 'm'){
res += 1;
}else{
res += 0;
};
};
return res;
};
console.log(stringToBinary(str));輸出
控制檯中的輸出結果如下 −
00001 111000 011 010 111
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP