1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
|
// Test code adjusted to build with Visual C++ 2019
//
// 1. char* p = "Some const string" is now an error
// so copy test strings into temp buffer to avoid changes to find_last()
// 2 strcpy() is deprecated, so #define _CRT_SECURE_NO_WARNINGS
// to avoid need for secure version of function (so still runs on C++ Shell)
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
// uncomment to run tests against strrchr rather than find_last
//#define CHECK_WITH_STRRCHR
void test_find_last();
char* find_last(char s[], char c);
int main()
{
test_find_last();
return 0;
}
char* find_last(char s[], char c)
{
char* last = nullptr;
char* p = s;
for (int i = strlen(s); i > 0; i--)
{
if (*(p + i) == c)
{
last = p + i;
}
}
return last;
}
// Test Code
void test_find_last()
{
struct test_data
{
const char* s;
char c;
};
static const test_data data[] = {
{"Hello", 'o'},
{"Hello", 'l'},
{"Hello", 'e'},
{"Hello", 'H'},
{"Hello", 'x'},
{"Hello, cplusplus.com", 'o'},
{"Hello, cplusplus.com", 'l'},
{"Hello, cplusplus.com", 'e'},
{"Hello, cplusplus.com", 'H'},
{"Hello, cplusplus.com", 'x'},
};
static const size_t test_data_count = sizeof(data) / sizeof(data[0]);
for (size_t i = 0; i < test_data_count; ++i)
{
const test_data& t = data[i];
char s_buff[64]{};
strcpy(s_buff, t.s);
#ifndef CHECK_WITH_STRRCHR
char* p = find_last(s_buff, t.c);
#else
char* p = strrchr(s_buff, t.c);
#endif
cout << "last \'" << t.c << "\' in \"" << t.s << "\" => " << (void*)p << " (";
if (p == nullptr)
{
cout << "<null>";
}
else
{
cout << "\"" << p << "\"";
}
cout << ")" << endl;
}
}
|