Hi, I'm doing a project where we make our own string class and I'm having trouble with the substring function. This is what I have so far.

string string::substr(size_type idx, int length)
    {   // can use the += char somewhere
        string *someString;
        char *ch = _data;
        for(idx = 0; idx < someString[length]; idx++){ 
            //someString[idx].operator+=(_data);
            someString[idx] += _data;
        }       

        return someString; // some string here
    }

And this is what my professor wants us to do:
substr - returns a string that is a substring of a string object It is given two ints, the first is the index of the first character of the substring and the second is the length of the substring.
This function can use += char.
I don't know if I have to allocate new memory and if so I don't know where to put it. Thanks in advance.

Recommended Answers

All 2 Replies

Member Avatar for iamthwee

A bit different but you get the idea, here int y is the end position as opposed to the length.

#include <iostream>
#include <iomanip> 
#include <string>

using namespace std;


void cut(string t,int x, int y)
{
 
   string build = "";
   
   for ( int i = x; i <= y; i++ )
   {
     build = build + t[i];
   }
   
   cout<<build;
}


int main()
{
  
  string test = "hello";
  
  cut("hello", 2,4);
  
  cin.get();
}

Thanks iamthwee, but the function needs to have 2 parameters not 3. How would I replace your string t parameter?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.