Sign in to follow this  

[Solved]substr() for char *

This topic is 4392 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Is there a function similar to the Cstring substr() function for char * ?? This is what the function should do: subchar(const char * , start,length) //prototype return a substring fromchar * start at position <start> and with the length <length> example: char * temp="test"; char * temp2 = subchar(temp,1,2); printf(temp2); does a similar function exist in c++ for char *?? [Edited by - Aidamina on December 3, 2005 6:10:57 AM]

Share this post


Link to post
Share on other sites
I assume you're using plain C:
const char temp[] = "test";
const char substring[10] = { 0 };
strncpy(substring, &temp[1], 2)
printf(substring);
If you're using C++ then Trap's solution is the best.

Share this post


Link to post
Share on other sites
Quote:
Original post by ZQJ
std::string(temp+start, length)

That's a bit faster than my version, especially if you only need a small part of the string and it works with char* that are not properly \0-terminated.

Share this post


Link to post
Share on other sites
Quote:
Original post by ZQJ
std::string(temp+start, length)


Just had a thought - if temp is not NULL terminated then the string MUST be longer than start+length; if it is NULL terminated the string must be longer than start otherwise this will break, where Trap's version won't.

Share this post


Link to post
Share on other sites

This topic is 4392 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this