এই প্রোগ্রামে একটি স্ট্রিংয়ে কতগুলো বিরাম চিহ্ন (punctuation) আছে সেটি গণনা করা হয়।
বিবেচিত বিরাম চিহ্ন
! , ; . - ? ' "
সমাধান
const countPunctuation = (str) => {
// সব বিবেচিত বিরাম চিহ্ন
const punctuations = new Set(['!', ',', ';', '.', '-', '?', "'", '"']);
let count = 0;
for (const char of str) {
if (punctuations.has(char)) {
count++;
}
}
return count;
};
// বিকল্প: রেগেক্স ব্যবহার
const countPunctuationRegex = (str) => {
const matches = str.match(/[!,;.\-?'"]/g);
return matches ? matches.length : 0;
};
// টেস্ট
const str = "This, is a-sentence;.Is this a sentence?";
console.log(countPunctuation(str)); // 5
console.log(countPunctuationRegex(str)); // 5
ব্যাখ্যা
- Set: O(1) লুকআপ টাইমের জন্য
- for...of: ইউনিকোড সাপোর্ট সহ ক্যারেক্টার ইটারেশন
- Regex: সংক্ষিপ্ত কিন্তু কিছুটা স্লোয়ার
বিস্তারিত বিরাম চিহ্ন তালিকা
যদি আরও বিরাম চিহ্ন যোগ করতে চান:
const extendedPunctuations = new Set([
'!', ',', ';', '.', '-', '?', "'", '"',
':', '(', ')', '[', ']', '{', '}',
'...', '—', '–', '¡', '¿'
]);
উৎপাদন
5