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 stringExplanation / 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;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.