In c++ please. Implement the function: string* createWordsArray (string sentence
ID: 3722081 • Letter: I
Question
In c++ please.
Implement the function:
string* createWordsArray (string sentence, int& outWordsArrSize)
This function gets a string sentence containing a sentence.
When called, it should create and return a new array (of strings), that contains all the words sentence. The function should also update the output parameter, outWordsArrSize, with the logical size of the new array that was created.
Note: Assume that the words in the sentence are separated by a single space.
For example, if sentence=”You can do it”, after calling createWordsArray(sentence, outWordsArrSize), the function should create and return an array that contains [”You” , ”can” , ”do” , ”it”], and update the value in outWordsArrSize to be 4.
Implementation requirements:
1.You may want to use some of the string methods, such as find, substr, etc.
2.Your function should run in linear time. That is, if sentence contains n characters, your function should run in theta (n).
3. Write a main() program that tests this function.
I keep getting the error, "cannot invoke char..."
Explanation / Answer
Program:
string* createWordsArray(string sentence,int& size)
{
//declare the pointer
string* word=new string;
int start,end,count=0;
//initialize start to zero and end to first occurence of character space
start=0;
end=sentence.find(' ');
while(end>0 && start<sentence.length())
{
//copy the substring to array
word[count]=sentence.substr(start,end-start);
count++;
start=end+1;
//find the next occurence of character space
end=sentence.find(' ',start);
}
if(start<sentence.length())
{
word[count]=sentence.substr(start,sentence.length()-start);
count++;
}
size=count;
return word;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.