فى هذا الموضوع سوف نتكلم عن طريقة عمل دالة لتقطيع أى جملة أو نص إلى كلمات منفردة , وسوف يتم تحديد رمز محدد يتم تقطيع الجملة أو النص من خلالة , وسيتم حفظ الناتج فى مصفوفة بحيث أن كل كلمة تم فصلها من الجملة يتم إضافتها فى مفتاح جديد للمصفوفة , وهذا لتسهيل التعامل مع كل مفتاح فى المصفوفة بشكل منفرد
فمثلا لدينا جملة كهذة .
Welcome to 0gate.com
عند إدخالها للدالة سيتم تقطيعها لكى يتم إخراج كل كلمة منفردة والرمز الذى سيفصل النص من خلالة هو المسافة , فستظهر الجملة بهذا الشكل .
Welcome To 0gate.com
تحتوى الدالة على معاملين:-
- معامل النص : وهو النص الذى نريد أن نفصل كل كلمة عن بعضها
- معامل الرمز: وهو الذى سيتم قطع النص من خلالة
وفى ما يلى نعرض لكم الكود الخاص بالدالة , مع طريقة أستخدامها .
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void splitSentence(char *, char); // a prototype of function
int main(){
splitSentence("Welcome to 0gate.com", ' ');
return 0;
}
void splitSentence(char *Sentence, char symb){
const int Size = strlen(Sentence);
string Sent;
string *SentenceResult = new string[Size];
int count= 0;
stringstream stream;
for(int i=0;i<=Size;i++){
stream << Sentence[i]; // Store every word in string stream
if((Sentence[i] == symb) || (Sentence[i] == '\0')){
Sent = stream.str(); // convert stringstream to string and store it in Sent variable
Sent.erase(Sent.end()-1); // Edit the Sent variable to erase the symbol from Sent variable
SentenceResult[count] = Sent; // Store next word in new key in array
count++; // Increase the count variable to go to next key in array
stream.str(""); // clear the stringstream
}
}
// display every word in line
for(int i=0;i<count;i++)
cout << SentenceResult[i] << endl;
}
نتمنى أن تكون الدالة سهلة وبسيطة وأن يكون الشرح مفهوم .