What is wcschr in C?
wcschr is a function in C defined in the wchar.h header file. It allows you to find the position of the first occurrence of a wide character inside a wide string.
It is to be noted that the string terminating character is also considered a part of the wide string, so it can also be found using the
wcschrfunction.
Syntax
This must not be confused with its overloaded counterpart in C++, where
wcschrcan also take awchar_t*argument instead of theconst wchar_t*argument in just C.
Parameters
wcschar takes in two arguments:
-
str: A pointer to a constant wide string,const wchar_t*, in which to search. -
ch: The wide character,wchar_t, whose position we need to find in the wide string pointed to.
Return values
wcschar has two possible return types:
-
A
wchar_t*pointer to the first occurrence of the wide character to find if it is present in the string. -
A
NULLpointer is returned if the required wide character is not present in the string.
Example
The following is an example where we show how you can find the index of a certain wide character in a wide string using the wcschr function:
#include <wchar.h>int main (){// declare and initialize a constant wide stringconst wchar_t * w_str= L"Educative has a ton of useful courses !!! ";// use wcschr function to find position of '!'// and store it in the found_ptr pointerwchar_t * found_ptr = wcschr(w_str,L'!');// find integer index by subtracting the 2 pointers and adding 1int position = found_ptr-w_str+1;// print positionwprintf (L"We found the first '!' at the %dth index of the string \n",position);return 0;}
Wide character strings are initialized exactly like character strings but have an ‘L’ just before the string starts
In the function, we declare and initialize a constant wide string, after which we find the first time ‘!’ appeared in the string using the wcschr function and stored the returning pointer in a wide-character pointer.
Finally, to generate the actual index of where ‘!’ was found, we subtract the two pointers. This actually returns the integer place behind the true index of ‘!’ so we add a 1 to get the real position.
Free Resources