Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments
Open

字符串中字母的出现次数 #112

Sunny-117 opened this issue Nov 3, 2022 · 5 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@GlintonLiao
Copy link

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

@bearki99
Copy link

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

@fencer-yd
Copy link

fencer-yd commented Jun 1, 2023

const reg = /[^a-zA-Z]/g;
const str = "ABCabc123";
console.log(str.replaceAll(reg, '').length)

@Banks1y
Copy link

Banks1y commented Jun 18, 2023

const str = "ABCabc123";
let res = str.split("").reduce((pre, cur) => {
  if (!pre[cur]) pre[cur] = 1;
  else pre[cur]++;
  return pre;
}, {});
console.log(res);

@kangkang123269
Copy link

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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants