Advertisement

How To Pull A Substring Out Of A Char * String?

Started by July 28, 2000 04:17 PM
11 comments, last by TipTup 24 years, 4 months ago
I posted the first one assuming a c++ compiler & no error checking, if you are using a c compiler it should read

char* substr(char* string, int begin, int end)
{
char* temp = (char *) malloc(sizeof(char)*(end-begin+1));
if(temp != NULL)
{
strncpy(temp,string+begin,end-begin+1);
temp[end-begin+1] = ''\0'';
}
return temp;
}

If that doesn''t work post how you are calling, because it works fine for me in a c++ and non c++ compiler assuming you''ve included string.h and call it correctly.


quote: Original post by TipTup

        void substr(char *string, int begin, int end, char *result){	result = (char *)malloc(end-begin+1);	strncpy(result, string+begin, end-begin+1);	result[end-begin] = 0;}        


I''m making progress with that but it still isn''t fully accurate.. lol

-TipTup
TipTup.Com


Ok, finally someone that doesn''t return a in function defined char[]...
Guys, if you define char[256] = "" inside a function, then return it, the memory shouldn''t even be valid by the time you use it, worst, you first declare a 256 char array, then make it point somewere else, efectivelly losing the 256 char memory, and using a one byte array. I''m just surprised if it hasn''t crashed on you.

TipTurn; i don''t see an error with this function. I could argue that allocating memory on a different level than the one you will be using it (inside a function, then returning it), is prone to memory loosing by forgetfullness. But hey, if you take care in dealloc''ing all the substring you get, then no prob.

P.S. silly me, the function won''t work, since the pointer inside is a local variable. try making it a (char *)&result (?)


You know, I never wanted to be a programmer...

Alexandre Moura
Advertisement


Try:

    #include <windows.h>void subString(const char *source, 			   int begin, 			   int end, 			   char *destination) {        //: FIXIT:		//: validate source	//: validate destination size	//: validate begin < end	int i = 0;	while ( begin <= end ) {		destination[i++] = source[begin++];	}}int main(int, char**) {	char test[80];	memset(test, 0L, sizeof(test));	subString("Hello, world", 3, 5, test);	return (0);}    


This topic is closed to new replies.

Advertisement