| TIP: Click on subject to list as thread! | ANSI |
| echo: | |
|---|---|
| to: | |
| from: | |
| date: | |
| subject: | Extraction of a substring |
JH> I have a string and I need to extract a substring of
JH> length n, starting at character number p.
There are no stupid questions except for the one's whose
answers embarrass me!
Check the mid() function in SNIPPETS. There is a whole suite
of BASIC-like string handling functions in there.
The following example allocates memory for the substring
being returned, and that memory must eventually be returned
to the OS or it will constitute a memory leak.
#include
#include
#include
char *extract_substring(char *S, int from, int bytes)
{
char *mid = malloc(bytes + 1);
if(NULL != mid)
{
memmove(mid, S + from, bytes);
mid[bytes] = (char)'\0';
}
return mid;
}
int main(void)
{
char base_string[] = "Example String... Serves no purpose.";
char *substring;
substring = extract_substring(base_string, 8, 9);
if(NULL == substring)
{
puts("Malloc error in extract_substring().");
return 1;
}
puts("substring should be equal to \"String...\"");
printf("substring = \"%s\".\n", substring);
free(substring);
return 0;
}
> ] * Origin: *YOPS ]I[* 8.4 GIG * RA/FD/FE * Milwaukee, WI (1:154/750)SEEN-BY: 396/1 622/419 632/0 371 633/260 267 270 371 634/397 635/506 728 810 SEEN-BY: 639/252 670/213 218 @PATH: 154/750 222 396/1 633/260 635/506 728 633/267 |
|
| SOURCE: echomail via fidonet.ozzmosis.com | |
Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.