Hey,
I would like to know 2 things.
1)Is there any function (in C standard library) that extracts a
substring from a string?
Yes, strncpy() can be made to copy a substring of one string
into another:
#include <string.h> /* for strncpy() */
#include <stdio.h> /* for printf() */
int
main(void)
{
char msg[] = "Hello World!";
char submsg[10]; /* Must be long enough */
/* Copy the substring "o W" from msg to submsg */
strncpy(submsg, &msg[4], 3);
/* Terminate the resulting string since strncpy() doesn't */
submsg[3] = '\0';
printf("msg[] = '%s'\nsubmsg[] = '%s'\n", msg, submsg);
return 0;
}
2)Is there any function (in C standard library) that returns the
position of a substring in a string?
No, but you may use strstr() like this:
#include <string.h> /* for strstr() */
#include <stdio.h> /* for printf(), fprintf() */
#include <stddef.h> /* for ptrdiff_t, NULL */
int
main(void)
{
char msg[] = "Hello World!";
char *ptr;
ptrdiff_t ptrpos;
/* Locate the substring "o W" in msg */
ptr = strstr(msg, "o W");
if (ptr == NULL) {
fprintf(stderr, "Substring not found\n");
} else {
/* Calculate the position of ptr in msg */
ptrpos = ptr - &msg[0];
printf("Position of 'o W' in '%s' is %d\n", msg, ptrpos);
}
return 0;
}
Wlcm a lot...