en,HString *Sub){
int i;
//判断位置和长度的合法性
if(pos < 1 || pos > S->length || len < 0 || len > S->length - pos + 1){
printf("子串的位置或长度不合法!\n");
exit(-1);
}
else{
Str_Clear(Sub);
if(len){
Sub->ch = (char *)malloc(len * sizeof(char));
for(i = 0;i < len;i++)
Sub->ch[i] = S->ch[pos + i -1];
Sub->length = len;
}
}
}
//在顺序串中找出给定子串给定位置后出现的第一个的位置
int Str_GetSubIndex(HString *S,HString *Sub,int pos){
int i,j;
//先判断位置的合法性
if(pos < 1 || pos > S->length){
printf("位置不合法!\n");
exit(-1);
}
if(Str_IsEmpty(S)){
printf("顺序串为空!\n");
return -1;
}
if(Str_IsEmpty(Sub)){
printf("给定子串为空,空串为任何串的子串!\n");
return 0;
}
for(i = pos - 1; i < S->length - Sub->length + 1;i++){
for(j = 0; j < Sub->length;j++)
if(S->ch[i+j] != Sub->ch[j])
break;
// 如果找到子串,则j= sub->length
if(j == Sub->length)
return i + 1;
}
//如果找不对,则返回-1;
return -1;
}
//顺序串中插入子串
void Str_Insert(HString *S,int pos,HString *T){
int i;
HString temp;
if(pos < 1 || pos > S->length){
printf("位置不合法!\n");
exit(-1);
}
if(Str_IsEmpty(T)){
printf("子串为空!\n");
exit(0);
}
Str_Init(&temp);
temp.length = S->length + T->length;
printf("%d\n",temp.length);
temp.ch = (char *)malloc(sizeof(char)*temp.length);
for(i = 0 ;i < pos ;i++)
temp.ch[i] = S->ch[i];
for(; i < pos + T->length;i++)
temp.ch[i] = T->ch[i - pos];
for(;i < temp.length;i++)
temp.ch[i] = S->ch[i - T->length];
//将串S 清空,并将串temp赋值给S
Str_Clear(S);
S->ch = temp.ch;
S->length = temp.length;
}
//在顺序串删除子串
void Str_DeleteSub(HString *S,int pos,int len){
int i;
HString temp;
//判断位置和长度的合法性
if(pos < 1 || pos > S->length || len < 0 || len > S->length - pos + 1){
printf("子串的位置或长度不合法!\n");
exit(-1);
}
if(Str_IsEmpty(S)){
printf("顺序串为空!\n");
exit(0);
}
Str_Init(&temp);
temp.length = S->length - len;
temp.ch = (char *)malloc(sizeof(char)*temp.length);
for(i = 0 ;i < pos - 1; i++)
temp.ch[i] = S->ch[i];
for(;i < temp.length;i++)
temp.ch[i] = S->ch[i+len];
//将串S清空,并将串temp赋值给S
Str_Clear(S);
S->ch = temp.ch;
S->length = temp.length;
}
//打印顺序串
void Str_Print(HString *S){
int i = 0;
if(Str_IsEmpty(S)){
printf("顺序串为空!\n");
exit(0);
}
else
printf("%s\n",S->ch);
}
|