I have a string of variable length. Each character is either ‘r’, ‘w’, or ‘x’.
I know how to use strpos() to find the position of the first occurrence of a character within a string. But I’d like to find the position of the first occurrence of either ‘r’ or ‘w’. Put another way, I’d like to find the position of the first occurrence of “not x”.
For example:
"rwxrxx" would return 0
"wxrr" would return 0
"xxwwwwwr" would return 2
"xxrx" would return 2
"xxxwrrwxxrrwxrrwwxrxrw" would return 3
The optimal way to do this (although with a small caveat) would be one of strspn() or strcspn(), but there’s a slight difference depending on exactly what you want to do …
If you want to find the first occurence of a character other than ‘x’, then you need
strspn():And if you need the first occurence of specifically ‘w’ or ‘r’, you’d need
strcspn():But as I said, there’s a small caveat … these functions return the initial length that matches or doesn’t match the given mask/needle (the ‘c’ in
strcspn()stands for “counter”).What this means is that they won’t ever return
falseand you’ll always get a positive result for e.g. ‘xxxxxxx’:Therefore, you may want to check if the returned position does really exist, like this:
Original answer: