问题描述:

题目标题:前缀判断
如下的代码判断 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这个指针指向的是原串,也就是例子里面的”abcd1234“,needle指针指向的是前缀,例子里面的”abc“。我们知道,在指针指向的是字符串的第一个元素

再来分析一下那个while循环,里面的条件是haystack指针和needle指针都没有越出边界,所以下面的if条件里面肯定涉及到指针的向后挪动,当什么时候返回NULL呢,很明显,就是当两个指针指向的元素不同时就结束调用,下面的if判断的是如果haystack先越界了,而needle还没有越界,那needle肯定就不可能是前缀了。

所以括号里面要完成两件事,一个是指针的内容是否相同,再是指针向后挪动,下面放程序

#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(*needle) return NULL;     
	
	return haystack_start;
}

int main ()
{
	
	cout<<prefix("abc123","cbc")<<endl;
	
	return 0;
}


立志成为一名攻城狮