কম্পিউটার টিউটোরিয়াল

C++-এ স্ট্রিংয়ে ওয়ার্ড কাউন্ট: স্পেস, নিউলাইন, ট্যাব হ্যান্ডলিং

একটি স্ট্রিং দেওয়া আছে যেখানে স্পেস, নিউলাইন (\n), ট্যাব (\t) দিয়ে ওয়ার্ডগুলো পৃথক। মোট কতটি ওয়ার্ড আছে তা গণনা করুন।

উদাহরণ

ইনপুট: "welcome to\n tutorials point\t"

ওয়ার্ড: welcome, to, tutorials, point → ৪টি

অ্যালগরিদম (স্টেট 머шин)

  1. inWord = false, count = 0
  2. প্রতিটি ক্যারেক্টার জন্য:
    • যদি whitespace (space/\n/\t): inWord = false
    • অন্যথায় যদি !inWord: inWord = true; count++

C++ বাস্তবায়ন


#include 
using namespace std;

int total_words(const string& str) {
    int count = 0;
    bool inWord = false;
    for (char c : str) {
        if (c == ' ' || c == '\n' || c == '\t') {
            inWord = false;
        } else if (!inWord) {
            inWord = true;
            count++;
        }
    }
    return count;
}

int main() {
    string str = "welcome to\n tutorials point\t";
    cout << "Words: " << total_words(str);
    return 0;
}

আল্টারনেটিভ: stringstream


#include 
int countWords(string str) {
    stringstream ss(str);
    string word;
    int count = 0;
    while (ss >> word) count++;
    return count;
}

স্মার্ট পয়েন্টার ভার্সন (C-স্টাইল)


int total_words(char* str) {
    int count = 0, inWord = 0;
    while (*str) {
        if (*str == ' ' || *str == '\n' || *str == '\t')
            inWord = 0;
        else if (!inWord) {
            inWord = 1;
            count++;
        }
        str++;
    }
    return count;
}
  1. C++-এ একটি স্ট্রিং সম-স্ট্রিং (sum-string) কিনা তা যাচাই করা

  2. C#-এ স্ট্রিংয়ে শব্দ গণনা করা (Word Count)

  3. C#-এ দেওয়া স্ট্রিংয়ের শব্দগুলো রিভার্স করা (Reverse Words)

  4. পাইথন প্রোগ্রাম: দেয়া স্ট্রিং-এ শব্দ গণনা (Count Words in a Given String)