In this guide, you will learn what is strchr() function is in C++ programming and how to use it with an example.
1. strchr() Function Overview
The strchr() function is part of the <cstring> library in C++ and is used to find the first occurrence of a specified character in a C-style string. This function returns a pointer to the first occurrence of the character, or NULL if the character is not found.
Signature:
const char* strchr(const char* str, int ch);
char* strchr(char* str, int ch);
Parameters:
- str: The string in which to search for the character.
- ch: The character to be searched.
2. Source Code Example
#include <iostream>
#include <cstring>
int main() {
const char* string = "Hello, World!";
char character = 'o';
char* result = strchr(string, character);
if(result != nullptr) {
std::cout << "First occurrence of '" << character << "' is found at position: " << (result - string + 1) << std::endl;
} else {
std::cout << "Character '" << character << "' not found in the string." << std::endl;
}
return 0;
}
Output:
First occurrence of 'o' is found at position: 5
3. Explanation
1. The <iostream> header is included for standard input/output and <cstring> for the strchr() function.
2. A string and a character are initialized, where we will search for the character within the string.
3. The strchr() function is used to find the first occurrence of the specified character in the string.
4. If the character is found, a pointer to its first occurrence is returned, and we calculate its position using pointer arithmetic. Otherwise, a nullptr is returned.
5. Appropriate messages are displayed based on the result.
The strchr() function is particularly useful when trying to find a character within a string and process subsequent characters or determine the character's position.
Comments
Post a Comment