In class and labs we have interacted with several C standard library functions f
ID: 3607683 • Letter: I
Question
In class and labs we have interacted with several C standard library functions for manipulating C-strings (strlen(), strcpy(), etc.).
In this problem you will implement the following function:
char* new_csubstr(const char* str,
unsigned int pos,
unsigned int len);
Given a valid input C-string (str), you should return a pointer to a newly allocated C-string that contains the substring starting at
str[pos] and ending at str[pos+len-1](inclusive). However, if the requested length would push past the end of the input string
str, then you should return a new string with contents from str[pos] to the end of str. You may assume that pos (the start
position) is a valid (in-bounds) index in the str array. You cannot change the contents of the input (str) array.
A few examples (assume NULL terminated C-strings):
char input1[] = "Hello world";
char input2[] = "USC";
new_csubstr(input1, 3, 4);// return a pointer to the C-string "lo w"
// (with NULL termination).
new_csubstr(input2, 0, 2);// return a pointer to the C-string "US"
// (with NULL termination).
new_csubstr(input2, 1, 8);// return a pointer to just the C-string
// "SC" (with NULL termination). Since
// the length is beyond the end we
// just return the portion that exists
// (i.e. “SC”).
The skeleton code contains the empty function (that you need to complete) and a main() with a few test calls to your function.
Your implementation may NOT use any of the library functions (strlen(), strcpy(), etc.). Your implementation must return a
pointer to a newly allocated C-string with proper NULL termination.
Explanation / Answer
Given below is the code with output. Please don't forget to rate the answer if it helped.
Thank you.
#include <iostream>
using namespace std;
char* new_csubstr(const char* str,
unsigned int pos,
unsigned int len);
int main()
{
char input1[] = "Hello world";
char input2[] = "USC";
cout << new_csubstr(input1, 3, 4) << endl;;// return a pointer to the C-string "lo w"
// (with NULL termination).
cout << new_csubstr(input2, 0, 2) << endl;// return a pointer to the C-string "US"
// (with NULL termination).
cout << new_csubstr(input2, 1, 8) << endl;// return a pointer to just the C-string
// "SC" (with NULL termination). Since
// the length is beyond the end we
// just return the portion that exists
// (i.e. “SC”).
}
char* new_csubstr(const char* str,
unsigned int pos,
unsigned int len)
{
int i , j;
char *sub = new char[sizeof(len) + 1]; //1 extra for null ternminator
for(i = pos, j = 0; str[i] != '' && j < len; i++, j++)
sub[j] = str[i];
sub[j] = '';
return sub;
}
=========
output
lo w
US
SC
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.