Search for a Character with strchr() in C++: Example & Complexity
This Snippet is coded by a user inOnline cpp Compiler. You can see and run this code too.
زبان: C++
std::strchr searches a null-terminated C string for the first occurrence of a character. Include <cstring> and call std::strchr(text, target), where text is a const char* or char* and target is an int representing the character to find. The function returns a pointer to the matching character, or nullptr if the character does not appear. For example, calling std::strchr on a C string with 'l' returns a pointer to the first l, while searching for 'x' returns nullptr. If target is '\0', it returns a pointer to the terminating null character. Because the result points inside the original buffer, subtract the original pointer from the result to compute a zero-based index. Inputs are a C-style string and a character; outputs are a pointer or nullptr. Use .c_str() to search a std::string, but do not modify the string while using the returned pointer. The search is case-sensitive, so 'A' and 'a' are different. Always check the returned pointer before dereferencing or performing pointer arithmetic. Its time complexity is O(n), where n is the number of characters examined before the match or terminating null is reached; space complexity is O(1). This makes strchr suitable for simple first-match searches in C-style strings, while std::string::find is often preferred for modern C++ string handling.