Sign in to follow this  
Aidamina

[Solved]substr() for char *

Recommended Posts

Aidamina    100
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
baumep    375
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
Trap    684
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
ZQJ    496
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

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