-
April 19th, 2009, 08:15 PM
#1
String class
Hello everyone.
I need help creating a substring function for my string class implementation.
Here is the substring function but it doesn't work.
Code:
String String::SubString(int startPosition, int count)
{
char* sub;
if (count == 0)
{
sub = new char [Length() - startPosition];
for(int i = startPosition; i < Length(); i++)
sub[i - startPosition] = Text[i];
}
else
{
sub = new char [count-startPosition];
for(int i = startPosition; i < count; i++)
sub[i - startPosition] = Text[i];
sub[count-startPosition]='\0';
}
String temp(sub);
return temp;
}
Could you please tell me what is wrong
-
April 19th, 2009, 08:27 PM
#2
Re: String class
Code:
sub = new char [count-startPosition];
to...
Code:
sub = new char [count+1];
-
April 19th, 2009, 09:02 PM
#3
Re: String class
count is the position of the last char from Text.
So for example, if there was a String temp="hello".
temp.Substring(1,4)
should return a String that has its char Text be "ell"
Could you please recheck my code
Thanks
-
April 19th, 2009, 09:30 PM
#4
Re: String class
I would suggest giving your class a constructor with the prototype
Code:
String(const char* str, int count)
Which initializes the string with the first count characters of str.
This would allow you to implement the substring function as something like:
Code:
String String::SubString(int start, int count)
{
assert(start < currentStringLength);
assert((start + count) <= currentStringLength);
return String(Text + start, count);
}
Also based on the code you posted I would suspect other potential problems with your class. When you create a string from a char*, does the class do an allocation internally to store the char array, or does it take ownership of the pointer that's passed to it (will it try to delete it in its destructor?)?
If the former, then the SubString function presented in the OP would have leaked memory every time it was called. If the latter, well, try this and see what happens:
Code:
int main( )
{
String str("Hello World!");
return 0;
}
-
April 19th, 2009, 10:26 PM
#5
Re: String class
Originally Posted by cwnelatury
I need help creating a substring function for my string class implementation.
Code:
sub = new char [Length() - startPosition];
Who is responsible for deleting this memory? There should be absolutely no direct memory allocation going on in a substring function.
The correct way, of course, is to use std::string and not re-invent the wheel by writing your own string class. If this is a school exercise, the proper way you do this is to construct a String given a pointer to a buffer and the number of characters, just as Speedo mentioned. Then you return that String you constructed.
Regards,
Paul McKenzie
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|