閱讀776 返回首頁    go 阿裏雲 go 技術社區[雲棲]


2013藍橋杯【初賽試題】前綴判斷

前綴判斷
如下的代碼判斷 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;
}

 

請分析代碼邏輯,並推測劃線處的代碼,通過網頁提交。
注意:僅把缺少的代碼作為答案,千萬不要填寫多餘的代碼、符號或說明文字!!

 

答案:*(haystack++)!=*(needle++)

解析(見注釋)注意:haystack為要判斷的字符串,needle為前綴。

char* prefix(char* haystack_start, char* needle_start)
{
 char* haystack = haystack_start;//標準串的指針 
 char* needle = needle_start;//要檢測的串的指針 

 
 while(*haystack && *needle){
    //因為比較的是兩個串的前綴是否相等,所以,要向後比較,要自加 
    //在needle指向的被檢測的串指向空時,對比就結束了 
    //例如haystack指向的是abc123,而needle指向的是abc
    //那麼當haystack指向1時,needle已經指完了,再指
    //就是null(空)了,此時 *haystack && *needle為null
    //while循環結束,比較結束 
     //倘若之前就有不相等的,那麼needle指向的串一定不是haystack串的前綴 
     //所以應該填寫下麵的代碼 
  if(*(haystack++)!=*(needle++)) return NULL;  //填空位置
 }
 
 if(*needle) return NULL;//如果此時是needle指針是空的,那麼返回空 
 
 return haystack_start;//其它情況均合格 
}



 

最後更新:2017-04-03 12:55:35

  上一篇:go HDU 4593 Robot
  下一篇:go Android 如何把狀態欄信號格改為5格