蓝桥杯——前缀判断

题目

如下的代码判断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;

能过编译之后,带着题目看代码,这题需要理解指针

  • while(*needle_start)意为当needle_start指向的位置不越界,不为空时为true,一直循环
  • if(*needle_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(*needle)
		return NULL;
	return haystack_start;
}

int main()
{
	cout<<prefix("agfgar23r","ag")<<endl;
	return 0;	
}

猜你喜欢

转载自blog.csdn.net/weixin_44078014/article/details/107609455
今日推荐