As mentioned in the comments, there are a lot of more convenient ways to split a string (strtok
, std functionality, etc.), but if we talk about your sample, you should not assign the 'str[i]' but append it, since it is a single character that you want to append to the current word like this:
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
if(str[i] == ' ' && !strWords[counter].empty()){
counter++;
}
else {
strWords[counter] += str[i];
}
}
But this will work only on the given input data, since you can access the array strWords
outside bounds if you have more than five words. Consider using a following code:
string str = "Welcome to the computer world.";
vector<string> strWords;
string currentWord;
for(short i=0;i<str.length();i++){
if(str[i] == ' ' && !currentWord.empty()){
strWords.push_back(currentWord);
currentWord.clear();
}
else {
currentWord += str[i];
}
}
UPDATE
Since I assume you are new to C++, here is the demonstration of the space issue you have (if you only use the addition operator):
#include <string>
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
string str = "Welcome to the computer world.";
string strWords[5];
short counter = 0;
for(short i=0;i<str.length();i++){
strWords[counter] += str[i]; // Append fixed
if(str[i] == ' '){
counter++;
}
}
for(short i=0;i<5;i++){
cout << strWords[i] << "(" << strWords[i].size() << ")" << endl;
}
return 0;
}
Result:
