Exercise 12
This commit is contained in:
51
Informatik_I/Exercise_12/Task_2b/README.org
Normal file
51
Informatik_I/Exercise_12/Task_2b/README.org
Normal file
@@ -0,0 +1,51 @@
|
||||
#+title: Task 2b: Understanding Pointers - First_Char
|
||||
#+author: JirR02
|
||||
|
||||
* 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
|
||||
|
||||
#+BEGIN_src shell
|
||||
jabberwock
|
||||
b
|
||||
#+END_src
|
||||
|
||||
** 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
|
||||
|
||||
#+BEGIN_src cpp
|
||||
#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;
|
||||
}
|
||||
#+END_src
|
||||
|
||||
--------------
|
||||
|
||||
Made by JirR02 in Switzerland 🇨🇭
|
Reference in New Issue
Block a user