-
-
Notifications
You must be signed in to change notification settings - Fork 230
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
字符串中字母的出现次数 #112
Comments
const str = "ABCabc123"
let res = 0
for (const c of str)
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
res++
console.log(res) // 6 |
function count(str){
let res = 0;
for(let i = 0; i < str.length; i++){
if(str[i] >= 'a' && str[i] <= 'z' || (str[i] >= 'A' && str[i] <= 'Z')) res++;
}
return res;
}
console.log(count("ABCabc123")); 如果是要统计每个字母的次数,可以用map |
const reg = /[^a-zA-Z]/g;
const str = "ABCabc123";
console.log(str.replaceAll(reg, '').length) |
const str = "ABCabc123";
let res = str.split("").reduce((pre, cur) => {
if (!pre[cur]) pre[cur] = 1;
else pre[cur]++;
return pre;
}, {});
console.log(res); |
function countCharacters(str) {
let charCount = {};
for(let i = 0; i < str.length; i++) {
let char = str[i];
if(char.match(/[a-zA-Z]/i)) { // 只考虑字母
if(charCount[char]) {
charCount[char]++;
} else {
charCount[char] = 1;
}
}
}
return charCount;
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: