CSCI 103L - Fall 2024 Introduction to Programming

Sample MT2 (Codio) Solutions

new_cstr problem solution

#include <iostream>
#include <algorithm> 
//********************
// You may NOT add other #includes
// You have to write other desired
//  functionality yourself
//********************
using namespace std;


// Complete the following function
//
// This function should return a **new**, correctly-formatted C-String
//  with size "length" (given by the input argument) and 
//  containing the substring from str[startPos] to str[startPos+length-1].
//
//  str         is a valid C-string. It should not be altered
//  startPos    starting index/position of the desired substring
//  length      is the desired length of the substring
//
// Return the pointer (start address) of the new array containing
//  the substring. You should always return a pointer to a valid
//  C-string even if the input arguments are invalid...see examples
//  below.
//
// ** You may NOT use any library functions in your implementation **
//
// Example 1:  csubstr("Hello world", 3, 4) should return "lo w"
// Example 2:  csubstr("USC", 0, 2) should return "US"
//
// if any part of the specified range of the substring falls out of
//  bounds of the input string, return a substring containing only
//  the valid portion.
//
// Example 3:  csubstr("USC", 1, 10) should return just "SC"
//                  since the length is beyond the end of "USC"
//
//

char* new_csubstr(char* str, int startPos, int length)
{
  int mylen=0;
  while(str[mylen] != '\0') mylen++;

  // we might waste some memory if `length` characters
  // cannot be extracted, but let's use the length given us
  char* retval = new char[length+1];
  int oidx = 0;
  int maxIndex = min(startPos+length, mylen);
  for(int i=startPos; i < maxIndex; i++){
    retval[oidx] = str[i];
    oidx++;
  }
  retval[oidx] = '\0';
  return retval;

}


//**************************************
// Do not change these 2 lines and don't
// add any lines between them and main()
//**************************************
#ifndef AUTO_TEST
#define AUTO_TEST
int main(int argc, char* argv[])
{
  //*********************************************************
  // Make test calls to your function here
  //*********************************************************
  char* result;
  result = new_csubstr("Hello world", 3, 4);
  cout << result << endl;
  delete [] result;

  result = new_csubstr("USC", 0, 2);
  cout << result << endl;
  delete [] result;

  return 0;  
}
//****************************************
// Do not change the following line
//****************************************
#endif