# Character String Function Assignment Solution with C++

July 10, 2024
Professor Nathan
🇺🇸 United States
C++
Professor Nathan Reynolds is a renowned C++ programming expert with a master's degree in computer engineering from Stanford University. With 900 assignments successfully completed, he excels in binary file processing and encryption algorithms. Professor Reynolds' in-depth knowledge and practical experience make him a valuable asset for tackling complex file handling tasks.
Key Topics
• Question:
Tip of the day
News

## 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; } ```

## Related Samples

Explore our collection of free C++ assignment samples to enhance your understanding. Access insightful examples that can guide you through various programming concepts and techniques.