Get index of substring
64,695
Solution 1
Use pointer subtraction.
char *str = "sdfadabcGGGGGGGGG";
char *result = strstr(str, "abc");
int position = result - str;
int substringLength = strlen(str) - position;
Solution 2
newptr - source
will give you the offset.
Solution 3
char *source = "XXXXabcYYYY";
char *dest = strstr(source, "abc");
int pos;
pos = dest - source;
Solution 4
If you have the pointer to the first char of the substring, and the substring ends at the end of the source string, then:
strlen(substring)
will give you its length.substring - source
will give you the start index.
Solution 5
Here is a C version of the strpos function with an offset feature...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strpos(char *haystack, char *needle, int offset);
int main()
{
char *p = "Hello there all y'al, hope that you are all well";
int pos = strpos(p, "all", 0);
printf("First all at : %d\n", pos);
pos = strpos(p, "all", 10);
printf("Second all at : %d\n", pos);
}
int strpos(char *hay, char *needle, int offset)
{
char haystack[strlen(hay)];
strncpy(haystack, hay+offset, strlen(hay)-offset);
char *p = strstr(haystack, needle);
if (p)
return p - haystack+offset;
return -1;
}
Author by
Country
Updated on November 08, 2020Comments
-
Country over 3 years
I have char * source, and I want extract from it subsrting, that I know is beginning from symbols "abc", and ends where source ends. With strstr I can get the poiner, but not the position, and without position I don't know the length of the substring. How can I get the index of the substring in pure C?