Tom
Tom

Reputation:

implement substring c++

how do you implement substring in C++ that returns pointer to char? (takes pointer to the first letter)

say something like char* substr(char* c, int pos, int lenght)

Upvotes: 0

Views: 4065

Answers (3)

ChrisW
ChrisW

Reputation: 56123

I use methods of the std::string class.


Edit:

say something like char* substr(char* c, int pos, int lenght)

This isn't a function that it's possible to implemement well. To create a substring, you need memory:

  • Same memory as original string: did you mean to overwrite the original string? Is the original string writeable?

  • New memory: is the caller going to invoke the delete[] operator on the pointer which it receives from your substr function (if it doesn't, there would be a memory leak)?

  • Global memory: you could reserve a fixed-length buffer in global memory, but that's all sorts of problems (may not be long enough, will be overwritten when someone else calls your substr).

The right way to do it is to return a std::string instance, which is what the string::substr method does, as shown in Graphics Noob's answer, because the std::string instance (unlike a char* instance) will manage the lifetime of its own memory; and if you then want a char* instance from the std::string instance, you can get that using the c_str() method.

Upvotes: 4

Graphics Noob
Graphics Noob

Reputation: 10070

str.substr(int,int).c_str()

Will return the substring as a const char* but be careful using it, the memory containing the string will be invalid at the end of the statement, so you may need to surround it with a strcpy() if you want to store the result. Or better yet just break it up into two lines:

std::string str2 = str.substr(int,int);
const char* cstr = str2.c_str();  

You'll need to do a strcpy() to safely get rid of the const.

The ints refer to the parameters for the substring you're trying to get.

Upvotes: 1

Igor Zevaka
Igor Zevaka

Reputation: 76590

Is this the functionality you are trying to replicate?

http://www.cplusplus.com/reference/clibrary/cstring/strstr/

Upvotes: 2

Related Questions