西电数据结构上机题——删除子串
【摘要】
好长时间不写代码了 问就是好久没上机了 明天又要上机 今晚赶紧肝完欠下的六道题
进入正题 好久没用C语言,发现C语言有个坑,字符串初始化不能和数组混淆 记录一下让我花费很多时间的一个错误 char te...
好长时间不写代码了
问就是好久没上机了
明天又要上机
今晚赶紧肝完欠下的六道题
进入正题
好久没用C语言,发现C语言有个坑,字符串初始化不能和数组混淆
记录一下让我花费很多时间的一个错误
char temp[40] 是数组
最后输出不当会导致白色方框的出现
char temp[40]=""是字符串
加引号会在末尾自动添加”\0”
话不多说 上代码
//删除子串的程序代码
#include<stdio.h>
#include<string.h>
#include<malloc.h>
//顺序串的结构类型定义
#define maxsize 100
typedef struct
{
char str[maxsize];
int len;
}seqstring;
void strPut(seqstring*);
void strDelete(seqstring*,int,int);
int main()
{
seqstring*S;
int i,m;
S=(seqstring*)malloc(sizeof(seqstring));
printf("输入串:"); gets(S->str);
S->len=strlen(S->str);
strPut(S);
printf("删除的开始位置:");scanf("%d",&i);
printf("删除的字符个数:");scanf("%d",&m);
strDelete(S,i,m);
strPut(S);
}
//输出串
void strPut(seqstring*S)
{
int i;
for(i=0;i<S->len;i++)
printf("%c",S->str[i]);
printf("\n");
}
//添加删除子串算法// m<=S->len-m+1
void strDelete(seqstring*S,int i,int m)
{
char temp[maxsize]="";
char temp2[maxsize]="";
if (i>=1 && i<=S->len)
{
if(i+m<=S->len)
{
strncpy(temp,S->str,i-1);
strncpy(temp2,S->str+i+m-1,S->len-m-i+1);
strcat(temp,temp2);
strcpy(S->str,temp);
S->len=S->len-m+1;
}
else
{
strncpy(temp,S->str,i-1);
strcpy(S->str,temp);
S->len=i;
}
}
else
{
printf("删除位置超过串长度,没有字符被删除,S为");
}
}
``
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
文章来源: zstar.blog.csdn.net,作者:zstar-_,版权归原作者所有,如需转载,请联系作者。
原文链接:zstar.blog.csdn.net/article/details/109630740
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)