Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Im having trouble with my programming assignment in C Write a function that take

ID: 3704141 • Letter: I

Question

Im having trouble with my programming assignment in C

Write a function that takes a string and splits it up to an array of strings. The split will be length-based: the function will also take an integer n and will split the given string up into strings of length n. It is possible that the last string will not be of length n. You will not need to communicate how large the resulting array is as the calling function knows the string length and n.

char **lengthSplit(const char *s, int n);

For example, if we pass "Hello World, how are you?" with n = 3 then it should return an array of size x containing the strings "Hel" , "lo " , "Wor" , "ld," , " ho" , "w a" , "re " , "you" , "?"

The answer needs to be in C

Explanation / Answer

Hi Dear,

Please find my implementation of required method:

char **lengthSplit(const char *s, int n){

char **arr;

int index=0;

int i, total, len;

len = strlen(s);

total = len/n + (len%n == 0 ? 0 : 1);

arr = (char **)malloc(sizeof(char *)*total);

for (i=0; i<len; i=i+n) {

arr[index] = (char *)malloc(sizeof(char)*n);

strncpy(arr[index], &s[i], n);

index++;

}

return arr;

}