USING - C++ Make a function that takes as an input a character array and an arra
ID: 3835686 • Letter: U
Question
USING - C++ Make a function that takes as an input a character array and an array of integers. This function should return a dynamically created string array, created by combining the char array into words of length denoted by the int array. More specifically, the first element in the integer array denotes how many characters from the character array comprise the first word. The second element in the integer array indicates that those many letters after the first word in the character array are the second word. And so on.... Example: char words[] = {'h', 'i', 't', 'h', 'e', 'r', 'e', 'c', 'l', 'a', 's', 's'}; int lens[] = {2, 5, 5};//The above input into your function should return a string array://{"hi", "there", "class";}Explanation / Answer
#include<iostream>
using namespace std;
string* getStrings(char c[], int l[]){
int n = sizeof(l) / sizeof(int);
string *str = new string[n+1];
int index = 0;
for(int j=0,i=0;i<n+1;i++){
string s = "";
index = index + l[i];
for(;j<index; j++){
s = s + c[j];
}
str[i]=s;
}
return str;
}
int main() {
char words[] = {'h','i','t','h','e','r','e','c','l','a','s','s'};
int lens[] = {2,5,5};
string *s= getStrings(words, lens);
int n = sizeof(lens) / sizeof(int);
for(int i=0;i<n;i++){
cout<<s[i]<<endl;
}
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
hi
there
class
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.