Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the index of a character within a string in C?

Tags:

c

indexing

strchr

Suppose I have a string "qwerty" and I wish to find the index position of the e character in it. (In this case the index would be 2)

How do I do it in C?

I found the strchr function but it returns a pointer to a character and not the index.

like image 947
bodacydo Avatar asked Jul 10 '10 02:07

bodacydo


People also ask

How do you get a certain index of a string in c?

Just subtract the string address from what strchr returns: char *string = "qwerty"; char *e; int index; e = strchr(string, 'e'); index = (int)(e - string); Note that the result is zero based, so in above example it will be 2.

How do you find the index of a certain character in a string?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do I find a particular character in a string in c?

The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search.

How do you find the last index of a character in a string in c?

Description. The strrchr() function finds the last occurrence of c (converted to a character) in string. The ending null character is considered part of the string.


1 Answers

Just subtract the string address from what strchr returns:

char *string = "qwerty"; char *e; int index;  e = strchr(string, 'e'); index = (int)(e - string); 

Note that the result is zero based, so in above example it will be 2.

like image 107
wj32 Avatar answered Sep 22 '22 18:09

wj32