Description
封装一个字符串类,用于存储字符串和处理的相关功能,支持以下操作:
STR::STR()构造方法:创建一个空的字符串对象。
STR::STR(const char *)构造方法:创建一个字符串对象,串的内容由参数给出。
STR::length()方法:返回字符串的长度。
STR::putline()方法:输出串的内容,并换行。
你设计一个字符串类STR,使得main()函数能够正确运行。
函数调用格式见append.cc。
append.cc中已给出main()函数。
Invalid Word(禁用单词)错误:“string”、“vector”等被禁用。
Input
输入有若干行,每行一个字符串。
Output
每组测试数据对应输出一行,包含两部分内容,首先是一个整数,表示输入串的长度,然后是输入的字符串,两者用一个空格分开。格式见sample。
Sample Input
A
123456789
Sample Output
0
12 Hello World!
1 A
9 123456789
HINT
Append Code
append.cc,
AC代码一
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class STR
{
private:
char* _a;
int _i;
public:
STR():_a(NULL),_i(0) {}//NULL是与地址相对应,如果为空字符串的话,直接将NULL赋值给该地址就好;//赋值空字符串的方法;
STR(char* a):_a(a)//函数中数据的类型可以不按题目要求的来,但是函数要按照题目中的要求;
{
_i=strlen(a);
}
int length()
{
return _i;
}
void putline()
{
if(_i==0)
cout<<endl;
else
cout<<_a<<endl;
}
};
int main()
{
STR e;
STR h("Hello World!");
char s[100001];
cout << e.length() << " ";
e.putline();
cout << h.length() << " ";
h.putline();
while(gets(s) != NULL)
{
STR str(s);
cout << str.length() << " ";
str.putline();
}
}
AC代码二
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
class STR
{
private:
char* _a;
int _i;
public:
STR():_a(NULL),_i(0) {}
STR(const char *a)//这里不能直接将a赋值给_a,因为两者类型不一样;
{
int i=0;
while(a[i]!='\0')
i++;
_i=i;
_a=new char[_i+1];//这里不能少;因为如果没有这一块的话,没有分配内存,却访问它的下标了
for(int j=0;j<_i;j++)
_a[j]=a[j];
_a[_i]='\0';//这里千万别忘记;
}
int length()
{
return _i;
}
void putline()
{
if(_i==0)
cout<<endl;
else
cout<<_a<<endl;
}
};
int main()
{
STR e;
STR h("Hello World!");
char s[100001];
cout << e.length() << " ";
e.putline();
cout << h.length() << " ";
h.putline();
while(gets(s) != NULL)
{
STR str(s);
cout << str.length() << " ";
str.putline();
}
}
1、NULL是与地址相对应,如果为空字符串的话,直接将NULL赋值给该地址就好;
2、不能分配内存就访问它的下标,这个时候必须要动态分配空间;
3、const char*和char*是不一样的类型,不能直接赋值;
4、不要忘记’\0’;