问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果
#include<iostream>
using namespace std;
typedef struct {
/* data */
char *ch;
int length;
}Str, *str;
int strassign(Str& str, char* ch); //调用格式srassign(str, "cur input")
int strlength(Str str);
int strcompare(Str s1, Str s2);
int concat(Str& str, Str str1, Str str2);
int substring(Str& substr, Str str, int pos, int len);
int clearstring(Str& str);
void strdispiay(Str str);
int main(){
str a = new Str;
str b = new Str;
str c = new Str;
strassign(*a, "HelloWorld");
strdispiay(*a);
cout << "a串的长度为:" << strlength(*a) << endl;
strassign(*b, "world!");
strdispiay(*b);
cout << "b串的长度为:" << strlength(*b) << endl;
//cout << strassign(b, "hello") << endl;
switch(strcompare(*a, *b) == 0? 0 : (strcompare(*a, *b) < 0? -1 : 1)){
case -1:
cout << "串b大" << endl;
case 0:
cout << "相等" << endl;
case 1:
cout << "串a大" << endl;
}
concat(*c, *a, *b);
strdispiay(*c);
cout << "c串的长度为:" << strlength(*c) << endl;
system("pause");
return 0;
}
int strassign(Str& str, char* ch){
if(str.ch)
delete(&str.ch);
int len = 0;
char *c = ch;
while (*c){
/* code */
++len;
++c;
}
if(len == 0){
str.ch = NULL;
str.length = 0;
return 1;
}
else{
str.ch = new char[len +1];
if(str.ch == NULL)
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 s1, Str s2){
for(int i = 0; i < s1.length && i < s2.length; ++i)
if(s1.ch[i] != s2.ch[i])
return s1.ch[i] - s2.ch[i];
return s1.length - s2.length;
}
int concat(Str& str, Str str1, Str str2){
if(str.ch){
delete(&str.ch);
str.ch = NULL;
}
str.ch = new char[str1.length + str2.length + 1];
if(str.ch == NULL)
return 0;
int i = 0;
while(i < str1.length){
str.ch[i] = str1.ch[i];
++i;
}
int j = 0;
while(j <= str2.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){
delete(&substr.ch);
substr.ch = NULL;
}
if(len == 0){
substr.ch = NULL;
substr.length = 0;
return 1;
}
else{
substr.ch = new 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){
delete(&str.ch);
str.ch = NULL;
}
str.length = 0;
return 1;
}
void strdispiay(Str str){
for(int i = 0; i < str.length; i++)
cout << str.ch[i];
cout << endl;
}
