僅從 JavaScript 中的字串中反轉子音
問題
我們要求編寫一個 JavaScript 函式,它以一個只包含小寫英語字母的字串作為唯一的引數。
該函式應構造一個新字串,其中子音的順序已反轉,母音保持其相對位置。
例如,如果函式的輸入為 -
const str = 'somestring';
那麼輸出應該為 -
const output = 'gomenrtiss';
示例
程式碼為 -
const str = 'somestring';
const reverseConsonants = (str = '') => {
const arr = str.split("");
let i = 0, j = arr.length - 1;
const consonants = 'bcdfghjklnpqrstvwxyz';
while(i < j){
while(i < j && consonants.indexOf(arr[i]) < 0) {
i++;
}
while(i< j && consonants.indexOf(arr[j]) < 0) {
j--;
}
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
let result = "";
for(let i = 0; i < arr.length; i++) {
result += arr[i];
}
return result;
};
console.log(reverseConsonants(str));輸出
控制檯中的輸出將是 -
gomenrtiss
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP