昨天无聊的时候写了一个带头帧和尾帧的字符串,然后输出时,去除头帧和尾帧,我想这不是分分钟的事哦,但是粗心的我忘记了限定的条件,所以写出来铭记自己,时刻须谨慎!
一:头帧和尾帧的长度限定,即规定的头尾帧之前和后面都没有字符
实例代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_SIZE 1024
void getstr(char str[], int len_head, int len_tail)
{
int i;
int j = 0;
char temp[MAX_SIZE];
for(i = 0; i < strlen(str); i++)
{
if(i >= len_head)
{
if(i < (strlen(str) - len_tail))
{
temp[j] = str[i];
j++;
}
}
}
temp[j] = '\0';
int k = 0;
printf("the del str is :\n");
for(k = 0; k < j ; k++)
{
printf("%c",temp[k]);
}
}
int main()
{
char str[MAX_SIZE];
char head[MAX_SIZE] = "head";
char tail[MAX_SIZE] = "tail";
printf("Please input str:\n");
/*使用gets时,定义的数组长度要大,避免造成数组越界*/
gets(str);
getstr(str,strlen(head),strlen(tail));
return 0;
}
结果:指定的头尾帧长度大小不能变
当头尾帧长度变时:输出的错误结果如下:
二:头帧和尾帧的长度可变,即在头帧和尾帧的标志位前后有数据不影响结果
实例代码:
/*****************************************************
copyright (C), 2016-2017, Lighting Studio. Co., Ltd.
File name:ChenYangYang Version:0.1 Date:2016/11/13
Description:去除一个字符串的头尾帧,长度不限
Funcion List:
*****************************************************/
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 1024
void find(char str[],char head[],char tail[])
{
int i = 0; /*str字符串的起始坐标*/
int j = 0;
int k = 0; /*tail的起始坐标*/
int times = 0; /*循环次数*/
int len_head; /*head的长度*/
int len_tail; /*tail的长度*/
int count_head = 0; /*记录次数*/
int count_tail = 0; /*记录次数*/
/*接收输出的字符,一定要初始化,不然输出合法的字符时,之前会有无用的乱码*/
char temp[MAX_SIZE] = {0};
len_head = strlen(head);
len_tail = strlen(tail);
while(str[i] != '\0') /*遍历str*/
{
if(str[i] == tail[k]) /*当str与尾帧的起始字符相等时,进入循环*/
{
count_tail++; /*记录与尾帧相等的次数*/
k++;
}
if(count_head == len_head)
{
/*当记录的次数与尾帧长度相等*/
if(count_tail == len_tail)
{
printf("the str is :");
/*输出合法字符串*/
for(times = 0; times <= (j - len_tail); times++)
{
printf("%c",temp[times]);
}
printf("\n");
}
temp[j] = str[i]; /*将str中除去头帧的字符赋给temp数组*/
j++;
}
else if(str[i] == head[j]) /*str字符与头帧起始字符相等时*/
{
count_head++;
j++;
}
else
{
j = 0;
k = 0;
count_head = 0;
count_tail = 0;
}
i++;
}
printf("no str!\n");
return ; /*无返回值*/
}
int main()
{
/*输入一个带头帧和尾帧的字符串*/
char str[MAX_SIZE];
char head[] = "head"; /*头帧标志符号*/
char tail[] = "tail"; /*尾帧标志符号*/
printf("Please input str");
scanf("%s",str);
find(str,head,tail);
return 0;
}
结果: