[Blue Bridge Cup] Exam Training 2013 C++A Group Question 5 Prefix Judgment

Prefix judgment 

Title: Prefix Judgment The
following code judges whether the string pointed to by needle_start is the prefix of the string pointed to by haystack_start, if not, it returns NULL.
For example: "abcd1234" contains "abc" as the prefix

char* prefix(char* haystack_start, char* needle_start)
{     char* haystack = haystack_start;     char* needle = needle_start;     while(*haystack && *needle){         if(______________________________) return NULL; //fill in the blank position     }     if(*needle ) return NULL;     return haystack_start; } Please analyze the code logic, and guess the code at the underline, and submit it through the web page. Note: Only use the missing code as the answer, do not fill in redundant codes, symbols or explanatory text


 
    



    

    



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

 

Problem analysis

When you find the place to be filled, you must move the pointer and check whether the characters pointed to by the pointer are equal.

Facing the fill-in-the-blank problem, first put the code in the compiler and try to compile it. Make a certain judgment on the code to be filled, and fill in the code around how to solve the problem.

#include <iostream>
using namespace std; 
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

char* prefix(char* haystack_start, char* needle_start)
{
	char* haystack = haystack_start;	//原串 
	char* needle = needle_start;	//前缀 
	
	
	while(*haystack && *needle){	//两个指针都没有越界 
//		if(______________________________) return NULL; //填空位置
//移动指针,判断是否相等
		if(*(haystack++)!= *(needle++)) 
			return NULL;
	}
	
	if(*needle) 
		return NULL;
	
	return haystack_start;
}

int main(int argc, char** argv) {
	cout << prefix("abc123", "abd");
	return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_44566432/article/details/115139087