স্ট্রিংয়ে নির্দিষ্ট স্পেশাল ক্যারেক্টার (বিরাম চিহ্ন) কতবার আছে সেটি গণনা।
বিবেচিত ক্যারেক্টার
! , ; . - ? ' "
সমাধান
const countSpecial = (str) => {
const specialChars = new Set('!,;.\-\'?"'.split(''));
// বা: new Set(['!', ',', ';', '.', '-', '?', "'", '"']);
let count = 0;
for (const char of str) {
if (specialChars.has(char)) count++;
}
return count;
};
// Regex ভার্সন
const countSpecialRegex = (str) => {
const matches = str.match(/[!,;.\-?'"]/g);
return matches ? matches.length : 0;
};
// টেস্ট
const str = "This, is a-sentence;.Is this a sentence?";
console.log(countSpecial(str)); // 5
console.log(countSpecialRegex(str)); // 5
// কাস্টম স্পেশাল ক্যারেক্টার
const countCustomSpecial = (str, chars = '!,;.-\'?"') => {
const set = new Set(chars.split(''));
return [...str].filter(c => set.has(c)).length;
};
ব্যাখ্যা
- Set: O(1) লুকআপ, ডুপ্লিকেট অটো-রিমুভ
- for...of: ইউনিকোড সেফ ইটারেশন
- Regex: সংক্ষিপ্ত, কিন্তু এস্কেপিং জটিল
ইউনিকোড স্পেশাল ক্যারেক্টার
// সব Unicode punctuation (P category)
const countAllPunctuation = (str) => {
return [...str].filter(c => /\p{P}/u.test(c)).length;
};
console.log(countAllPunctuation("Hello, 世界!")); // 2 (, and !)
উৎপাদন
5