Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Subtract String problem

Status
Not open for further replies.

TanyaB

Programmer
Aug 15, 2001
18
IL
Hi,
I have very long string, pointer to start of sub-string inside it and pointer to end of sub-string ... How can I extract the substring ?
 
Your question is a bit unclear - do you want to extract the substring into a separate string leaving the substring intact in the original string or do you wish to take the substring out completely? If the latter, do you want the substring preserved or just droppped completely?

Rough code for option 1 follows - no error checking is done - you may have to tweak a bit to tidy it up and it is not complete...

void extract_string(char * string, char * start, char * end)
{
char * ptr1;
char * ptr2;
char * substring;
int len;

/* Work out length of substring + 1 for trailing null */
len=(end-start)+1;
/* Allocate memory for sub-string */
substring=(char *) malloc(len);
/* Point to start of sub-string */
ptr1=start;
/* Point to start of area to receive substring */
ptr2=substring;
/* Loop until we get to the end pointer. Copy 1 bytes
at a time from the source string into the new area */
do
*(ptr2++)=*(ptr1++);
while(ptr1!=end);
/* Add terminating NULL */
*ptr2=0x00;
Now you have to work out how to return the substring
and how to free the malloc'ed area later on.

The other options are variations on the above.....

Hope this gets you started/.
 
if you have the situation

char bigbuff[MAXBUFF]; and bigbuff is loaded say:

.....................abbbx............

and you have a ponter on 'a' and one on 'x'

in destructive mode( yoo loose the contents of bigbuff)
strcpy(bigbuff,pointer_on_a);
bigbuff[1+pointer_on_x - pointer_on_a] = 0;

in non destructive mode:
alloc a string len = pointer_on_x - pointer_on_a;
strncpy(newstring,&bigbuff[pointer_on_a],pointer_on_x - pointer_on_a); ------------ jamisar
Einfachheit ist das Resultat der Reife. (Friedrich Schiller)
Simplicity is the fruit of maturity.
 
If you are using the second method posted by jamisar, remember to put in the '\0'. This is one of the common gotchas: strncpy does not put in a terminator.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top