Reputation: 9087
I have two strings:
prettyCoolString
CoolString
I want to only get the part that says pretty
. I looked through the C string functions, but I cannot find out how to find the position of CoolString in prettyCoolString.
In Java, I can just find where CoolString appears in prettyCoolString, but with C, all I can do is return a pointer to the place where it begins. I want to find the position so I can just read the first x characters from prettyCoolString.
Here is what I mean by first part: I want to get the contents of the first string that appear before the second string appears in the first string.
Upvotes: 0
Views: 4048
Reputation: 182734
Try something like this:
char *source = "prettyCoolString";
char *find = "CoolString";
char dest[LENGTH];
char *p = strstr(source, find);
strncpy(dest, source, p - source);
Upvotes: 3
Reputation: 234857
Once you have a pointer to the first character past the "first part" (which you say you know how to do, presumably with strstr
), you can use it in several ways to extract the first part into a separate string. For instance:
char *substring(char *start, char *stop, char *dst, size_t size)
{
int count = stop - start;
if ( count >= --size )
{
count = size;
}
sprintf(dst, "%.*s", count, start);
return dst;
}
Upvotes: 0
Reputation: 96167
" all I can do is return a pointer to the place where it begins"
That and the length tells you pretty much all you need.
Use strstr() (or one of it's family) to search for the string if you don't know where it is.
strncpy() will copy that part to a new string.
Upvotes: 2