C语言:两头堵模型的有效字符串长度 以及提取出两头堵模型中的有效字符串

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>


int main01()
{
	const char* p = "       abcdefgHH       ";
	int begin = 0;
	int end = strlen(p) - 1;
	int n = 0;//字符串长度

	//从左往右
	//如果当前字符为空格,且字符串没有查找结束
	while (isspace(p[begin]) && p[begin] != 0)//也可以 (p[begin]==' ' && p[begin] != 0)
	{
		begin++;//位置从左往右移动一位
	}

	//从右往左
	//如果当前字符为空格,且字符串没有查找结束
	while (isspace(p[end]) && p[end] != 0)
	{
		end--;//位置从右往左移动一位
	}
	n = end - begin + 1;

	printf("n=%d\n", n);
	return 0;
}

//封装为函数
int fun(const char* p, int* n)
{
	if (p == NULL || n == NULL)
	{
		return -1;
	}
	int begin = 0;
	int end = strlen(p) - 1;

	//从左往右
	//如果当前字符为空格,且字符串没有查找结束
	while (isspace(p[begin]) && p[begin] != 0)//也可以 (p[begin]==' ' && p[begin] != 0)
	{
		begin++;//位置从左往右移动一位
	}

	//从右往左
	//如果当前字符为空格,且字符串没有查找结束
	while (isspace(p[end]) && p[end] != 0)
	{
		end--;//位置从右往左移动一位
	}
	*n = end - begin + 1;

	return 0;
}

int main02()
{
	const char* p = "       abcdefgHH       ";//字符串两端的空格数量一致

	int n = 0;//字符串长度
	int ret = 0;
	ret = fun(p, &n);//求非空格的字符串长度
	if (ret != 0)
	{
		return ret;
	}
	printf("n=%d\n", n);
	return 0;
}


int fun2(const char* p, char *buf)
{

	if (p == NULL || buf == NULL)
	{
		return -1;
	}
	int begin = 0;
	int end = strlen(p) - 1;
	int n = 0;

	//从左往右
	//如果当前字符为空格,且字符串没有查找结束
	while (isspace(p[begin]) && p[begin] != 0)//也可以 (p[begin]==' ' && p[begin] != 0)
	{
		begin++;//位置从左往右移动一位
	}

	//从右往左
	//如果当前字符为空格,且字符串没有查找结束
	while (isspace(p[end]) && p[end] != 0)
	{
		end--;//位置从右往左移动一位
	}

	n = end - begin + 1;

	strcpy(buf, p + begin, n);
	//补字符串结束符\0
	buf[n] = 0;

	return 0;
}

int main()
{
	const char* p = "       abcdefgHH       ";//字符串两端的空格数量一致
	char buf[100] = { 0 };
	int n = 0;//字符串长度
	int ret = 0;
	ret = fun2(p, buf);//提取出两头堵模型中的字符串,并存入buf中
	if (ret != 0)
	{
		return ret;
	}
	printf("buf=%s\n", buf);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值