首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

。字符串

2012-04-11 
求助。。。字符串#includeiostreamusing namespace stdclass String{private:char *strint sizepublic:S

求助。。。字符串
#include<iostream>
using namespace std;

class String
{
private:
char *str;
int size;
public:
String();
String(char *chx);
~String(){};
void Creat();
void Display();
void Insert(String s, int pos);
void Delete(int pos,int num);
String SubString(int pos, int num);
int Find(String T, int pos);
};
//无参构造函数
String::String()
{
str = new char;
if(!str)
cout << "\n分配不成功!" << endl;
size = 0;
str[0] = '\0';
}
//有参构造函数
String::String(char *chx)
{
size = strlen(chx);
str = new char[size];
if(!str)
cout << "\n分配不成功!" << endl;
strcpy(str, chx);
}
//创建字符串
void String::Creat()
{
char ch1[] = "*******************************";
cout << "\nInput String:";
cin >> ch1;
size = strlen(ch1);
str = new char[size + 1];
strcpy(str, ch1);
}
//输出字符串
void String::Display()
{
cout << "\noutput the string:";
cout << str << endl;
}
//在某个位置删除字符串
void String::Delete(int pos, int num)
{
pos--;
if(pos < 0 || pos >= size)
cout << "\n position error!";
else
{
if(pos + num > size)
size = pos;
else
{
for(int i = pos + num; i < size; i++)
str[i-num] = str[i];
size = size - num;
}
str[size] = '\0';
}
}
//在某一个位置插入字符串
void String::Insert(String s, int pos)
{
char *x = " ";
pos--;
if(pos < 0 || pos > size)
cout << "\nposition error!";
else
{
int size0 = size + s.size;
strcpy(x, str);
delete []str;
str = new char[size0 + 1];
strcpy(str, x);
for(int i = size - 1; i >= pos; i--)
str[i+s.size] = str[i];
for(int j = 0; j < s.size; j++)
str[pos+j] = s.str[j];
size = size0;
str[size] = '\0';
}
}
//求子串,返回子串对象
String String::SubString(int pos, int num)
{
String tp;
pos--;
if(pos < 0 || pos >= size || num <= 0)
return tp;
int left = size - pos + 1;
if(num > left)
num = left;
delete []tp.str;
tp.str = new char[num + 1];
for(int i =0,j = pos; i < num; i++,j++)
tp.str[i] = str[j];
tp.str[num] = '\0';
tp.size = num;
return tp;
}

void main()
{
String str1,str2,str3("good!");
str1.Creat();
str2.Creat();
str1.Display();
cout << endl;
str2.Display();
cout << endl;
str3 = str1.SubString(3,5);
str3.Display();
cout << endl;
str1.Delete(3,5);
str1.Display();
cout << endl;
str1.Insert(str2,3);
str1.Display();
}


[解决办法]

C/C++ code
//在某一个位置插入字符串void String::Insert(String s, int pos){    char *x ;    pos--;    if(pos < 0 || pos > size)        cout << "\nposition error!";    else    {        x =new char[size+1];        int size0 = size + s.size;        strcpy(x, str);        delete []str;        str = new char[size0 + 1];        strcpy(str, x);        for(int i = size - 1; i >= pos; i--)            str[i+s.size] = str[i];        for(int j = 0; j < s.size; j++)            str[pos+j] = s.str[j];        size = size0;        str[size] = '\0';        delete []x;    }}
[解决办法]
在学习些string类啊 呵呵 顶一个

热点排行