Member-only story

In C++, create a method that finds a character in a c style string using pointers

Marika Lam
2 min readMay 22, 2022

--

Question

Create a method that searches through str for the character chr. If the chr is found, it returns a pointer into str where the character was first found, otherwise nullptr (not found).

Explanation

findTheChar method has 2 parameters, an array of char, which is the c style string, and chr, which is the character to find in the string. Within the method, there is a for loop which iterates from 0 until a null terminator is found.

Within the for loop, check if the current iterated character, retrieved by *(str+k) is equal to the character. ‘*’ symbol is used to get the value where the pointer is currently pointing at. Once the character is found in the string, return the pointer where the character is found.

Code

#include <iostream>using namespace std;const char* findTheChar(const char str[], char chr){//str[k] is the same as *(str+k)for (int k = 0; *(str+k) != 0; k++)if (*(str+k) == chr){cerr << str[k] << endl;return str+k;}return nullptr;}int main(){char str[3] = {'a','b','c'};

--

--

No responses yet