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

Without using the string method substr, implement your own function substring (s

ID: 3629783 • Letter: W

Question

Without using the string method substr, implement your own function substring (s, pos, len), which returns the substring of s, beginning at position pos and including at most len characters. Make sure that your function correctly applies the following rules: If pos is negative, it is set to 0 so that it includes the first character in the string If len is greater than s.length () - pos, it is set to s.length () - pos so that it stops at the last character If pos is greater than s. length () - 1, substring returns the empty string

Explanation / Answer

//#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

string SubString(string str, int pos, int len);
int main(int argc)
{
    string str = "hello";
    string str2="";
    cout << SubString(str,0,2) << endl;
    cout << str.substr(0,2) << endl<<endl;
    cout << SubString(str,7,2) << endl;
    cout << str.substr(7,2) << endl<<endl; //Creates Error
    cout << SubString(str,0,7) << endl;
    cout << str.substr(0,7) << endl<<endl;
    return 0;
}

string SubString(string str, int pos, int len){
    unsigned int position;
    unsigned int length;
    string result="";
    if (pos<0) {
        position=0;
    } else if(pos>str.length()-1) {
        return result;
    } else{
        position = pos;
    }
    if (len>str.length()-position){
        length = str.length()-position;
    } else {
        length=len;
    }
    for(unsigned int x = 0; x < length;x++ ){
        //cout << str[position] << endl;
        result=result+str[position++];
    }
    return result;
   
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote