題目描述:
題目標題:前綴判斷
如下的代碼判斷 needle_start指向的串是否爲haystack_start指向的串的前綴,如不是,則返回NULL。
比如:"abcd1234" 就包含了 "abc" 爲前綴
char* prefix(char* haystack_start, char* needle_start)
{
char* haystack = haystack_start;
char* needle = needle_start;
while(*haystack && *needle){
if(______________________________) return NULL; //填空位置
}
if(*needle) return NULL;
return haystack_start;
}
請分析代碼邏輯,並推測劃線處的代碼,通過網頁提交。
注意:僅把缺少的代碼作爲答案,千萬不要填寫多餘的代碼、符號或說明文字!!
解決方案:
#include<iostream>
using namespace std;
char* prefix(char* haystack_start, char* needle_start)
{
char* haystack = haystack_start;
char* needle = needle_start;
while(*haystack && *needle){
// if( haystack++ == needle++ ) return NULL; //填空位置
if(*(haystack++) != *(needle++)) return NULL;
}
if(*needle) return NULL;
return haystack_start;
}
int main(){
printf("%s",prefix("abcd123","abc"));
return 0;
}