In: Computer Science
This C++ assignment asks to write a function that determines if a C-string begins with a specified prefix. It should have the following signature:
bool starts(char *str, char *prefix)
It should return true if str begins with prefix, false if not. It should return false if prefix is longer than str. See the table below for some examples of what your function should return for various cases:
str | prefix | returns |
airplanes | air | true |
airplanes | abc | false |
airplanes | plane | false |
airplanes | airplane | true |
air | airplane | false |
Assume that the pointers passed to it are pointers to valid,
null-terminated C-Strings. If you wish, you can use the strlen()
and strcmp() functions, but it isn't required.
Hint: it can make things easier to check if length of prefix > length of str. If so, you can immediately return false! If not, you can continue on with your check.
#include <iostream>
#include <cstring>
using namespace std;
bool starts(char *str, char *prefix)
{
int len1=strlen(str),len2=strlen(prefix);
char temp[len2+1];
if(len2>len1)
return false;
int i=0;
while(i<len2)
{
temp[i]=*(str+i);
i++;
}
temp[i]='\0';
if(strcmp(temp,prefix)==0)
return true;
return false;
}
int main()
{
char str1[100],str2[100];
cin>>str1>>str2;
cout<<std::boolalpha<<starts(str1,str2)<<endl;
return 0;
}