Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

string

char

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

like image 806
JAN Avatar asked May 18 '12 11:05

JAN


People also ask

How do you check if a char exists 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 can I check if a single character appears in a string?

You can use string. indexOf('a') . If the char a is present in string : it returns the the index of the first occurrence of the character in the character sequence represented by this object, or -1 if the character does not occur.

How do you check if a char is in a word in c?

The strchr function returns a pointer to the first occurrence of character c in string or a null pointer if no matching character is found.

Can you display a single character as a value in c?

yes, %c will print a single char: printf("%c", 'h'); also, putchar / putc will work too.


1 Answers

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");
like image 183
Adriano Repetti Avatar answered Sep 20 '22 03:09

Adriano Repetti