Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of substring

Tags:

c

substring

char

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?

like image 228
Country Avatar asked Sep 21 '11 13:09

Country


People also ask

Which string method returns the index position of a substring?

int indexOf(String str, int strt) : This method returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

Which function returns the starting index of the substring?

IndexOf(String substring, int startindex) This Java substring indexOf() method returns the index of the first character in the substring passed as the first parameter, after the “startindex” index value.

What does indexOf return?

The indexOf() method returns the position of the first occurrence of a value in a string. The indexOf() method returns -1 if the value is not found. The indexOf() method is case sensitive.


2 Answers

Use pointer subtraction.

char *str = "sdfadabcGGGGGGGGG"; char *result = strstr(str, "abc"); int position = result - str; int substringLength = strlen(str) - position; 
like image 53
Robert S. Barnes Avatar answered Oct 02 '22 12:10

Robert S. Barnes


newptr - source will give you the offset.

like image 42
Matt K Avatar answered Oct 02 '22 14:10

Matt K