I would like to point to a certain part of a character array, i.e:
char string[] = "the quick brown fox jumps over the lazy dog";
char * pointer = points to the 'fox' part of string;
Is this possible to do without using strncpy or something similar?
CodePudding user response:
Without copying or modifying the string, you can only point to substrings with the same end (e.g., fox jumps over the lazy dog
, dog
, or lazy dog
), not ones that end in the middle of the original string like fox
or lazy
.
CodePudding user response:
strstr()
or similar user code can be used to find a sub-string within a string.
const char *haystack = "the quick brown fox jumps over the lazy dog";
const char *target = "fox";
char *needle = strstr(haystack, target);
To print a portion of the string like "fox"
, use a precision.
if (needle == NULL) {
printf("<%s> not found.\n");
} else {
size_t offset = needle - haystack;
int precision = (int) strlen(target);
printf("<%.*s> found at offset %zu.\n", precision, needle, offset);
}