একটি স্ট্রিং দেওয়া আছে যেখানে স্পেস, নিউলাইন (\n), ট্যাব (\t) দিয়ে ওয়ার্ডগুলো পৃথক। মোট কতটি ওয়ার্ড আছে তা গণনা করুন।
উদাহরণ
ইনপুট: "welcome to\n tutorials point\t"
ওয়ার্ড: welcome, to, tutorials, point → ৪টি
অ্যালগরিদম (স্টেট 머шин)
inWord = false,count = 0- প্রতিটি ক্যারেক্টার জন্য:
- যদি whitespace (space/\n/\t):
inWord = false - অন্যথায় যদি
!inWord:inWord = true; count++
- যদি whitespace (space/\n/\t):
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;
}