Programming C++  «Prev 

String Equality in C++ - Exercise

Write a string equality test

Objective:Write a function that implements a string equality test.

Background

Pointers to char strings are by convention terminated with the value \0. The following function implements a string equality test. Note its use of pointer arithmetic. The construct *s1++ means dereference the pointer s1, and after using this value in the expression, add 1 to its pointer value.

bool streq(const char* s1, const char* s2)
{
 while (*s1 != 0 && *s2 != 0)
   if (*s1++ != *s2++)
     return false;
 return (*s1 == *s2);
}

Instructions

Write and test a function
bool strneq(const char* s1, const char* s2, int n);

that returns true if the first n characters of the two strings are the same and otherwise returns false.
Paste the source code of your function below and click the Submit button when you are ready to submit this exercise.