主函数如何写charvalue; //构造函数//拷贝构造函数//析构函数 //赋值函数,如setValue(charnewvalue) //返回有效字符的个数//返回某个位置的字符//替换某个位置的字符//选做:合并两个字符串,如 Concat(MyString&) //主函数如何写
时间: 2023-05-25 20:07:01 浏览: 83
,charsecondString); //选做:在字符串中查找某个字符或子串的位置,如 find(charsub) 或 find(MyStringsubString);
class MyString{
private:
char* str;
int size;
public:
MyString(){
str = new char[1];
str[0] = '\0';
size = 0;
}
MyString(const char* s){
size = strlen(s);
str = new char[size+1];
for(int i=0; i<=size; i++)
str[i] = s[i];
}
MyString(const MyString& other){
size = other.size;
str = new char[size+1];
for(int i=0; i<=size; i++)
str[i] = other.str[i];
}
~MyString(){
delete[] str;
}
MyString& operator=(const MyString& other){
if(this == &other)
return *this;
delete[] str;
size = other.size;
str = new char[size+1];
for(int i=0; i<=size; i++)
str[i] = other.str[i];
return *this;
}
void setValue(char newvalue){
str[0] = newvalue;
size = 1;
}
int getValidSize() const{
return size;
}
char getChar(int pos) const{
if(pos >= size)
return '\0';
return str[pos];
}
void replaceChar(int pos, char c){
if(pos >= size)
return;
str[pos] = c;
}
MyString Concat(const MyString& other) const{
MyString result;
result.size = size + other.size;
result.str = new char[result.size+1];
int i=0;
for(; i<size; i++)
result.str[i] = str[i];
for(; i<result.size; i++)
result.str[i] = other.str[i-size];
return result;
}
int find(const char* sub) const{
int sub_size = strlen(sub);
for(int i=0; i<=size-sub_size; i++){
int j=0;
while(j<sub_size && str[i+j]==sub[j])
j++;
if(j==sub_size)
return i;
}
return -1;
}
int find(const MyString& sub) const{
return find(sub.str);
}
};
阅读全文