How can I check if a single char exists in a C string?
Asked Answered
T

2

23

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)?

Tumblebug answered 18/5, 2012 at 11:42 Comment(3)
"|" is a c string, Anything enclosed in double quotes ", " is a string irrespective of number of characters it has.Either your Q title is misleading or I mis-understand your Q.Darell
@Als: Correct, fixed. thanks !Tumblebug
Note that '>>' is not a single character. Here you need a different approach (strstr).Praseodymium
M
30

If you need to search for a character you can use the strchr function, like this:

char* pPosition = strchr(pText, '|');

pPosition will be NULL if the given character has not been found. For example:

puts(strchr("field1|field2", '|'));

Will output: "|field2". Note that strchr will perform a forward search, to search backward you can use the strrchr. Now imagine (just to provide an example) that you have a string like this: "variable:value|condition". You can extract the value field with:

char* pValue = strrchr(strchr(pExpression, '|'), ':') + 1;

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 uses strnspn for this.

Instead if you're looking for a string you can use the strstr function, like this:

char* pPosition = strstr(pText, "text to find");
Margarite answered 18/5, 2012 at 11:44 Comment(0)
P
6

strchr is your friend.

char *strchr(const char *s, int c);

The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s.

The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.

And of course, the function has to walk through the whole string in the worst case (as the Java function probably does).

Praseodymium answered 18/5, 2012 at 11:45 Comment(2)
In constant strchr, c should be char type. I think mistakenly you typed int. It should be: char *strchr(const char *s, char c);Mcmahan
@Vibhuti: No, it should not. Please check the link in my answer or - in case you don't trust it - the ISO C standard, e.g.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf, page 330.Praseodymium

© 2022 - 2024 — McMap. All rights reserved.