#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;
}
C语言:两头堵模型的有效字符串长度 以及提取出两头堵模型中的有效字符串
最新推荐文章于 2021-11-24 13:02:16 发布