#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
/*
* Created by HarvestWu on 2018/6/1.
*/
using namespace std;
typedef struct Str
{
char *ch; //指向动态分配存储区首地址的字符指针
int length; //串长度
}Str;
//串赋值
int strAssign(Str &str,char *ch)
{
if(str.ch)
free(str.ch);
int len=0;
char *c=ch;
while (*c) //求ch串长度
{
++len;
++c;
}
if(len==0)
{
str.ch= nullptr;
str.length=0;
return 1;
}
else
{
str.ch=(char*)malloc(sizeof(char)*(len+1));
if (str.ch== nullptr)
return 0;
else
{
c=ch;
for (int i = 0; i < len; ++i,++c)
{
str.ch[i]=*c;
}
str.length=len;
return 1;
}
}
}
//获取串长度
int strLength(Str str)
{
return str.length;
}
//串比较
int strCompare(Str str1,Str str2)
{
for (int i = 0; i < str1.length&& i < str2.length; ++i)
{
if(str1.ch[i] != str2.ch[i])
return str1.ch[i] - str2.ch[i];
}
return str1.length - str2.length;
}
//串连接
int concat(Str &str,Str str1,Str str2)
{
if (str.ch)
{
free(str.ch);
str.ch= nullptr;
}
str.ch = (char*)malloc(sizeof(char)*(str1.length+str2.length+1));
if(str.ch== nullptr)
return 0;
int i = 0;
while (i < str1.length)
{
str.ch[i] = str1.ch[i];
++i;
}
int j = 0;
while (j <= str1.length)
{
str.ch[i+j] = str2.ch[j];
++j;
}
str.length = str1.length + str2.length;
return 1;
}
int subString(Str &subStr,Str 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= nullptr;
}
if(len==0)
{
subStr.ch= nullptr;
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';
subStr.length=len;
return 1;
}
}
//串清空
int clearString(Str &str)
{
if(str.ch)
{
free(str.ch);
str.ch= nullptr;
}
str.length=0;
return 1;
}
void display(Str str)
{
for (int i = 0; i < str.length; ++i)
{
printf("%c",str.ch[i]);
}
printf("\n");
}
int main()
{
char *s;
s= const_cast<char *>("this is str1");
Str str1,str2;
strAssign(str1,s);
printf("str1 is:\n");
display(str1);
printf("the length of str1 is: %d\n",strLength(str1));
s= const_cast<char *>("this is str2");
strAssign(str2,s);
printf("str2 is:\n");
display(str2);
printf("the length of str2 is %d\n",strLength(str2));
Str str;
concat(str,str1,str2);
printf("the concat str is: \n");
display(str);
Str subStr;
subString(subStr,str1,1,3);
printf("the subString is: \n");
display(subStr);
clearString(str2);
printf("the length of str2 is: %d\n",strLength(str2));
}
C++ 串操作
最新推荐文章于 2023-09-07 21:24:56 发布