+1 (315) 557-6473 

Character String Function Assignment Solution with C++


Question:

Write a C++ assignment function that takes two character strings (char arrays) as parameters and checks whether and how often the second character string is contained in the first. The function should return the number of occurrences of the second character string found in the first and, in a reference parameter, also return a pointer to the character in the first character string at which the first occurrence of the second character string begins (nullptr, if the second character string is not included ).

Solution:

#include < cstring> #include < iostream> using namespace std; char* check(char* first, char* second, int &num) { char* ptr = nullptr; num = 0; int len = strlen( second ); bool is_match; for ( int i = 0; i < strlen(first) - len + 1; ) { is_match = true; for ( int j = 0; j < len; j++ ) { if ( *( first + i + j ) != *( second + j ) ) { is_match = false; break; } } if ( is_match ) { if ( num == 0 ) { ptr = first + i; } num++; i += len; } else { i += 1; } } return ptr; } int main(int argc, char** argv) { char* first = (char*)"abc yee yee def ghi yee"; char* second = (char*)"yee"; int num; char* ptr = check(first, second, num); cout << "First string = " << first << endl; cout << "Second string = " << second << endl; cout << "Address of the first string = " << reinterpret_cast(first) << endl; cout << "Address of first occurrence of the second string in the first string = " << reinterpret_cast(ptr) << endl; cout << "Number of occurrences of the second string in the first string = " << num << endl; cout << endl; second = (char*)"ghi"; ptr = check(first, second, num); cout << "Second string = " << second << endl; cout << "Address of first occurrence of the second string in the first string = " << reinterpret_cast(ptr) << endl; cout << "Number of occurrences of the second string in the first string = " << num << endl; cout << endl; second = (char*)"123"; ptr = check(first, second, num); cout << "Second string = " << second << endl; cout << "Address of first occurrence of the second string in the first string = " << reinterpret_cast(ptr) << endl; cout << "Number of occurrences of the second string in the first string = " << num << endl; cout << endl; return 0; }