C++ wcsrchr()

The wcsrchr() function in C++ searches for the last occurrence of a wide character in a wide string.

The wcsrchr() function is defined in <cwchar> header file.

wcsrchr() prototype

const wchar_t* wcsrchr( const wchar_t* str, wchar_t ch );
wchar_t* wcsrchr( wchar_t* str, wchar_t ch );

The wcsrchr() function takes two arguments: str and ch. It searches for the last occurrence of the wide character ch in the wide string pointed to by str.


wcsrchr() Parameters

  • ptr: Pointer to the null terminated wide string to be searched for.
  • ch: Wide character to search for.

wcsrchr() Return value

If ch is found, the wcsrchr() function returns a pointer to the last location of ch in str, otherwise returns a null pointer.


Example: How wcsrchr() function works?

#include <cwchar>
#include <clocale>
#include <iostream>
using namespace std;

int main()
{
	setlocale(LC_ALL, "en_US.utf8");
	
	wchar_t str[] = L"\u222b\u222e\u2231\u2211\u220f\u222b";
	wchar_t ch = L'∫';// Integral sign
	wchar_t* p = wcsrchr(str, ch);
	
	if (p)
		wcout << L"Last position of " << ch << L" in \"" << str << "\" is " << (p-str);
	else
		wcout << ch << L" is not present \"" << str << L"\"";
	
	return 0;
}

When you run the program, the output will be:

Last position of ∫ in "∫∮∱∑∏∫" is 5
Did you find this article helpful?