在 JavaScript 中重组字符串中的字符
问题
我们需要编写一个 JavaScript 函数,该函数接受一个字符串 str 作为第一个也是唯一的参数。
字符串 str 可以包含三种类型的字符 −
英文字母:(A-Z)、(a-z)
数字:0-9
特殊字符 − 所有其他剩余字符
我们的函数应迭代此字符串并构建一个数组,该数组恰好包含三个元素,第一个包含字符串中出现的所有字母,第二个包含数字,第三个包含特殊字符,保持字符的相对顺序。我们最终应该返回此数组。
例如,如果输入函数为
输入
const str = 'thi!1s is S@me23';
输出
const output = [ 'thisisSme', '123', '! @' ];
示例
以下是代码 −
const str = 'thi!1s is S@me23';
const regroupString = (str = '') => {
const res = ['', '', ''];
const alpha = 'abcdefghijklmnopqrstuvwxyz';
const numerals = '0123456789';
for(let i = 0; i < str.length; i++){
const el = str[i];
if(alpha.includes(el) || alpha.includes(el.toLowerCase())){
res[0] += el;
continue;
};
if(numerals.includes(el)){
res[1] += el;
continue;
};
res[2] += el;
};
return res;
};
console.log(regroupString(str));输出
[ 'thisisSme', '123', '! @' ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP