I want to check if a single char is in a C string. The character is the '|'
used for pipelines in Linux (Actually, I also want to check for '<', '>', '>>', '&').
In Java I can do this:
String.indexOf()
But how can I do this in C, without looping through the whole string (a char* string)?
If you need to search for a character you can use the
strchrfunction, like this:pPositionwill beNULLif the given character has not been found. For example:Will output: “|field2”. Note that
strchrwill perform a forward search, to search backward you can use thestrrchr. Now imagine (just to provide an example) that you have a string like this: “variable:value|condition”. You can extract the value field with:If what you want is the index of the character inside the string take a look to this post here on SO. You may need something like
IndexOfAny()too, here another post on SO that usesstrnspnfor this.Instead if you’re looking for a string you can use the
strstrfunction, like this: