[Solved]substr() for char *

Started by
5 comments, last by Aidamina 18 years, 4 months ago
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]
-->My Site<--
Advertisement
std::string(temp).substr(pos,length);
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.
baumep
std::string(temp+start, length)
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.
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.
Thx for the info
-->My Site<--

This topic is closed to new replies.

Advertisement