数据结构学习笔记(3)串的插入的c++实现

 实现了向一个字符串中插入另一个字符串,这边的字符串时自己定义的类型。

如再aasdasd中的第2个位置插入ppp,就变为aapppsdasd;

// HSTRING.cpp: 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "type.h"
#include <Windows.h>
#include<iostream>
#include<stdio.h>
using namespace std;
class HString
{
public:
	HString();
	~HString();
	Status StrInsert(int pos, HString T) {
	//将T插入到本对象的pos位置
		if (pos<1 || pos>length - 1)return ERROR;
		if (T.ch)//如果T非空
		{
			char * ch_tmp = new char[length + T.length];
			memcpy(ch_tmp, ch, length);
			for (int i = length - 1; i >= pos - 1; i--) {
				ch_tmp[i + T.length] = ch_tmp[i];
			}
			//现在pos..。length已经空了,下面进行插入
			for (int i = 0; i <T.length; i++) {
				ch_tmp[pos+i] = T.ch[i];
			}
			ch = ch_tmp;
			length = length + T.length;
		}
		return OK;
	}
	Status StrAssign(char * chars) {
		if (ch) delete ch;
		int count=0;
		char * chars_temp = chars;
		while (*chars_temp !='\0') {
			
			count++;
			chars_temp++;
		}
		//cout << count;
		if (!count) { ch = NULL; length = 0; }//如果要复制的chars为空
		ch = new char[count];
		if (!ch) return ERROR;
		for (int i = 0; i < count; i++) {
			ch[i] = chars[i];	
		}
		//std::cout << std::endl;
		
		length = count;
		return OK;

	}

	void StrPrint() {
	//打印
		std::cout << "打印的字符串为:";
		for (int i = 0; i < length;i++ ) {
		
			std::cout << ch[i];
			
		}
		std::cout <<std::endl;
		
	}
private:
	char *ch;
	int length;
};

HString::HString()
{
}

HString::~HString()
{
}

int main()
{
	HString myString;
	HString insertStr;
	
	char * insertchars = (char *)"fuck";
	insertStr.StrAssign(insertchars);
	char * stq = (char *)"1234567";
	myString.StrAssign(stq);
	myString.StrPrint();
	myString.StrInsert(2, insertStr);
	cout << "after insert:";
	myString.StrPrint();
	cout << endl;
	system("pause");
    return 0;
}

运行结果ruxi如下图所示:

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值