JirR02 99962171df Exercise 12
Added Exercise 12 to Repo
2025-05-23 22:56:38 +02:00
..
2025-05-23 22:56:38 +02:00

Task 2b: Understanding Pointers - First_Char

Task Description

Complete the definition of function first_char by editing the file first_char.cpp according to its specified pre- and post conditions.

We provide a test program using the implemented function to find the index of the first character in a string.

Input

The program accepts

  • a string s (it may contain whitespaces), followed by a newline, and
  • a character c for which to search for the index first occurence

For example

jabberwock 
b

Output

The pointer to the first element at string s where it is equal to character c.

If there is no match, returns a null pointer.

Solution

#include "first_char.h"

// PRE: str points within an allocated memory block which contains
//      the null character (numerical ASCII value 0) at its last location,
//      and nowhere else.
// POST: Returns the pointer to first element at str or after
//       that is equal to ch, otherwise return nullptr.
const char *first_char(const char *str, const char ch) {
  for (;; str++)
    if (*str == ch)
      return str;
    else if (*str == '\0')
      return nullptr;
}

Made by JirR02 in Switzerland 🇨🇭