This tutorial will discuss about a unique way to check if char array starts with a string.
To check if a char array starts with another string or char array, we can follow the following steps,
- Get the number of characters in first char array.
- Get the number of characters in second char array.
- Make sure that the number of characters in first char array is either equal to or greater than the number of characters in second char array.
- Use the
strncmp()
function to compare the first N characters of both the char arrays, where N is the number of characters in the second char array. - If “strncmp()” returns 0, then it means that the string in first char array starts with the string in the second char array.
Let’s see the complete example,
#include <iostream> #include <string.h> // Check if a char array contains a character bool startWith( const char * arr, const char* substring) { bool result = false; // get number of characters in substring size_t subStrLen = strlen(substring) ; // get number of characters in char array string size_t mainStrLen = strlen(arr); // Check if char array starts with the given substring if( mainStrLen >= subStrLen && strncmp(arr, substring, subStrLen) == 0) { result = true; } return result; } int main() { char mainStr[50] = "This is a sample text"; char subString[50] = "This"; // Check if Char Array starts with a substring if(startWith(mainStr, subString) ) { std::cout<<"Char Array starts with a substring \n"; } else { std::cout<<"Char Array does not starts with a substring \n"; } return 0; }
Output :
Char Array starts with a substring
Summary
Today we learned about several ways to check if char array starts with a string. Thanks.