c++实现字符串操作
// 串操作.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream>
#include<string>
#define max 100
using namespace std;
class MyString
{
private:
char *str;
int length;
public:
MyString(const char *str_);
~MyString();
int getlen(); //获取字符串长度
void insert(int position, const char *str_); //插入字符串
void remove(int beginposition, int endposition); //删除字符串
void update(int beginposition, int endposition, const char *str_); //更新字符串
void display(); //打印字符串
char search(int position); //按位置取字符
};
MyString::MyString(const char *str_)
{
int i;
str = new char[max];
for (i = 0; str_[i] != '\0'; i++)
str[i] = str_[i];
length = i;
}
MyString::~MyString()
{
delete[] str;
}
int MyString::getlen()
{
return length;
}
void MyString::insert(int position, const char *str_)
{
int str_length = MyString(str_).getlen();
for (int i = 0; i < length - position + 1; i++)
str[length + str_length - 1 - i] = str[length - 1 - i]; //移动
for (int i = 0; i < str_length; i++)
str[position - 1 + i] = str_[i]; //插入
length = str_length + length; //更新长度
}
void MyString::remove(int beginposition, int endposition)
{
for (int i = 0; i < length - beginposition + 1; i++)
str[beginposition - 1 + i] = str[endposition + i]; //删除
length = length - (endposition - beginposition + 1); //更新长度
}
void MyString::update(int beginposition, int endposition, const char *str_)
{
int i = 0;
int str_length = MyString(str_).getlen();
int len = (endposition - beginposition) + 1;
if (len == str_length) //分三种情况
{ //先移动再覆盖
for (i = 0; i < len; i++)
str[beginposition - 1 + i] = str_[i];
}
else if (len < str_length)
{
for (i = 0; i < length - endposition + 1; i++)
str[length + str_length - len - 1 - i] = str[length - 1 - i];
for (i = 0; i < str_length; i++)
str[beginposition - 1 + i] = str_[i];
length = length + str_length - len;
}
else
{
for (i = 0; i < length - endposition; i++)
str[endposition - (len - str_length) + i] = str[endposition + i];
for (i = 0; i < str_length; i++)
str[beginposition - 1 + i] = str_[i];
length = length + str_length - len;
}
}
void MyString::display()
{
for (int i = 0; i < length; i++)
cout << str[i];
cout << endl;
}
char MyString::search(int position)
{
return str[position-1];
}
int main()
{
MyString s("abcdefghijk");
s.display();
cout << s.search(3) << endl;
s.insert(2, "123");
s.display();
s.remove(2, 4);
s.display();
s.update(2, 4, "123");
s.display();
s.update(2, 4, "1234");
s.display();
s.update(2, 5, "123");
s.display();
system("pause");
return 0;
}