String Functions with Pointers

String Functions with Pointers

char orgName[100] = “The Dept. of Redundancy Dept.”;
char newText[100];
char* subString = nullptr;

strchr()strchr(sourceStr, searchChar)

Returns null pointer if searchChar does not exist in sourceStr. Else, returns pointer to first occurrence.

if (strchr(orgName, 'D') != nullptr) { // 'D' exists in orgName?
subString = strchr(orgName, 'D'); // Points to first 'D'
strcpy(newText, subString); // newText now "Dept. of Redundancy Dept."
}
if (strchr(orgName, 'Z') != nullptr) { // 'Z' exists in orgName?
... // Doesn't exist, branch not taken
}
strrchr()strrchr(sourceStr, searchChar)

Returns null pointer if searchChar does not exist in sourceStr. Else, returns pointer to LAST occurrence (searches in reverse, hence middle 'r' in name).

if (strrchr(orgName, 'D') != nullptr) { // 'D' exists in orgName?
subString = strrchr(orgName, 'D'); // Points to last 'D'
strcpy(newText, subString); // newText now "Dept."
}
strstr()strstr(str1, str2)

Returns char* pointing to first occurrence of string str2 within string str1. Returns null pointer if not found.

subString = strstr(orgName, "Dept"); // Points to first 'D'
if (subString != nullptr) {
strcpy(newText, subString); // newText now "Dept. of Redundancy Dept."
}