#include <stdio.h>
#include <malloc.h>
#include <string.h>
//串的顺序存储
//堆分配存储
typedef struct
{
char *ch; //指向动态分配存储区首地址的字符指针
int length; //串长度
}HString;
/**************初始化***************/
void InitString(HString *s)
{
s->ch = NULL;
s->length = 0;
}
/***************字符串赋值*************/
void StrAssign(HString *s, char *ch)
{
int len = strlen(ch); //字符串的长度
//char *c = ch;
//判断字符串是否为空,不为空则释放
if (s->ch)
free(s->ch);
//判断赋值的内容是否为空,为空则不赋值
if (!len)
{
s->ch = NULL;
s->length = 0;
}
//根据串的长度向内存申请空间,赋值给串s
else
{
s->ch = (char*)malloc(sizeof(char)*len);
if (s->ch == NULL)
return 0;
else
{
for (int i = 0; i < len; ++i)
{
s->ch[i] = ch[i];
//printf("%c", s->ch[i]);
}
s->length = len;
return 1;
}
}
}
/******************打印字符串******************/
void printString(HString s)
{
for (int i = 0; i < s.length; i++)
printf("%c", s.ch[i]);
printf("\n");
}
/*****************取串长度**************/
int strlength(HString s)
{
printf("串的长度是%d\n",s.length);
}
/***************串比较操作**************/
int strcompare(HString s1, HString s2)
{
for (int i = 0; i < s1.length && i < s2.length; i++)
{
if (s1.ch[i] != s2.ch[i])
printf("%d\n", s1.ch[i] - s2.ch[i]);
else
printf("%d\n",s1.length - s2.length);
}
}
/*******************串连接操作******************/
int concatString(HString *str,HString s1, HString s2)
{
if (str->ch)
{
free(str->ch);
str->ch = NULL;
}
str->ch = (char*)malloc(sizeof(char)*(s1.length + s2.length + 1));
if (str->ch == NULL)
return 0;
int i = 0;
while (i < s1.length)
{
str->ch[i] = s1.ch[i];
++i;
}
int j = 0;
while (j <= s2.length) //用“<=”是为了连同最后的'\0'一起复制
{
str->ch[i + j] = s2.ch[j];
++j;
}
str->length = s1.length + s2.length;
return 1;
}
/*****************求子串操作******************/
//求str串中从pos位置开始,长度为len的子串
int subString(HString *substr, HString str, int pos, int len)
{
if (pos < 0 || pos >= str.length || len<0 || len>str.length - pos)
return 0;
if (substr->ch)
{
free(substr->ch);
substr->ch = NULL;
}
if (len == 0)
{
substr->ch = NULL;
substr->length = 0;
return 1;
}
else
{
substr->ch = (char*)malloc(sizeof(char)*len + 1);
int i = pos;
int j = 0;
while (i < pos + len)
{
substr->ch[j] = str.ch[i];
++i;
++j;
}
substr->ch[j] = '\0'; //给个位置给'\0'
substr->length = len;
return 1;
}
}
/***************串清空操作****************/
int clearString(HString *str)
{
if (str->ch)
{
free(str->ch);
str->ch = NULL;
}
str->length = 0;
return 1;
}
int main()
{
HString str,str1,s1,s2;
InitString(&s1);
StrAssign(&s1,"input");
printString(s1);
strlength(s1);
InitString(&s2);
StrAssign(&s2, "put");
printString(s2);
strlength(s2);
strcompare(s1, s2);
InitString(&str);
concatString(&str, s1, s2);
printString(str);
InitString(&str1);
subString(&str1, s1, 2, 2);
printString(str1);
clearString(&str1);
strlength(str1);
system("pause");
}