# Thread: How to search a string for a word/character and return its position?

1. ## How to search a string for a word/character and return its position?

If I had a string, say: "This is a string"

How would I search for a particular word or character and get it's position into an integer?

For instance, say I wanted to get the position of "a", which would be 3. Or if I wanted the position of "is" which is 2.

I know how to return the position of a character in a string like this: "a b c d e f g" using a for loop, and within the for loop, counting the number of spaces. But that is using a simple compare of the current character with the desired character.

I am confused how to do this when you have a mix of characters and words.

2. strstr returns a pointer to the position of the word in the string. After I have this pointer, do I then use that pointer in a for loop and count the number of spaces from the pointer until the end of the string, then do some math:

(total number of spaces) - (number of spaces after word) = (number of spaces before word)

Is that the idea?

Also, if I am searching a string of single characters and words ie: "a b c foo d e f foo", I need to tell it what string to search for. Can I specify a string with length of one? ie:

char str[] = "b";

3. Maybe this can help.
Code:
```char *str = "This is a string";
char *tmp = strstr(str, "string");
int space = 0;
for (int i=0; i<str - tmp; i++) if (str[i] == ' ') space++;```

4. Originally Posted by NewbGuy
strstr returns a pointer to the position of the word in the string
you can subtract pointers in one array