linux c之判断字符串是不是以另一字符串开始或者结尾

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/u011068702/article/details/97174348

1 问题

判断字符串是不是以另一字符串开始或者结尾

 

 

 

 

 

 

2 代码实现

#include <stdio.h>
#include <string.h>

/**
 *判断是字符串str是不是以start开始
 */
int is_start_with(const char *str, char *start)
{
	if (NULL == str || NULL == start)
	{
		return -1;
	}
	int str_len = strlen(str);
	int start_len = strlen(start);
	if (str_len < start_len || str_len == 0 || start_len == 0)
	{
		return -1;
	}
	char *p = start;
	int i = 0;
	while(*p != '\0')
	{
		if (str[i] != *p)
		{
			return -1;
		}
		++p;
		++i;
	}
	return 0;
}

/**
 *判断是字符串str是不是以end结束
 */
int is_end_with(const char *str, char *end)
{
	if (NULL == str || NULL == end)
	{
		return -1;
	}
	int str_len = strlen(str);
	int end_len = strlen(end);
	if (str_len < end_len || str_len == 0 || end_len == 0)
	{
		return -1;
	}	
	while (end_len > 0)
	{
		if (str[str_len - 1] != end[end_len - 1])
		{
			return -1;
		}
		--str_len;
		--end_len;
	}
	return 0;
}

int main()
{
	const char *str = "chenyu";
	char *first_str = "chen";
	char *second_str2 = "yu";
	int first_result = is_start_with(str, first_str);
	int second_result = is_start_with(str, second_str2);
	printf("first_result is  %d\nsecond_result is %d\n", first_result, second_result);
	int third_result = is_end_with(str, first_str);
	int fourt_result = is_end_with(str, second_str2);
	printf("third_result is  %d\nfourt_result is %d\n", third_result, fourt_result);
	return 0;
}

 

 

 

 

 

 

3 运行结果

first_result is  0
second_result is -1
third_result is  -1
fourt_result is 0

 

展开阅读全文

没有更多推荐了,返回首页