C++实现串的最小操作子集

本文探讨如何使用C++实现串的基本操作,通过精简操作子集来提高效率。内容涵盖字符串创建、拼接、查找、替换等关键功能的实现方法,并讨论了这些操作的性能优化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * HString.h
 *
 *  Created on: Oct 7, 2015
 *      Author: chris
 */

#ifndef HSTRING_H_
#define HSTRING_H_

#include<iostream>

struct HString{
	int length;
	char *ch;

	HString(): length(0), ch(NULL) {}
};

bool StrAssign(HString &hs, char *str);
void StrClr(HString &hs);

int  StrLen(HString hs);
bool SubStr(HString& Sub, HString S, int len, int pos);

int  StrCmp(HString &lhs, HString &rhs);
bool StrCat(HString &lhs, HString &rhs);

void StrPrint(HString str);

int  Index()

#endif /* HSTRING_H_ */



/*
 * HString.cpp
 *
 *  Created on: Oct 7, 2015
 *      Author: chris
 */

#include<iostream>
#include"HString.h"

using namespace std;

bool StrAssign(HString &S, char *str)
{
	if(S.ch) delete S.ch;
	char *ch = str;
	int cnt = 0;
	while(*ch++) ++cnt;
	if(cnt != 0) {
		S.ch = new char[cnt];
		if(!S.ch) return false;
		for(int i = 0; i < cnt; ++i)
			S.ch[i] = str[i];
	}
	S.length = cnt;
	return true;
}

void StrClr(HString &S)
{
	if(S.ch) delete S.ch;
	S.length = 0;
}

int  StrLen(HString S)
{
	return S.length;
}

bool SubStr(HString& Sub, HString S, int len, int pos)
{
	if(pos < 0 || pos >= S.length || len < 0 || pos+len > S.length)
		return false;

	if(Sub.ch) delete Sub.ch;
	Sub.ch = new char[len];
	if(!Sub.ch) return false;

	for(int i = 0; i < len; ++i)
		Sub.ch[i] = S.ch[pos+i];
	Sub.length = len;
	return true;
}

int  StrCmp(HString &lhs, HString &rhs)
{
	if(lhs.length != rhs.length)
		return lhs.length - rhs.length;

	for(int i = 0; i < lhs.length; ++i) {
		if(lhs.ch[i] != rhs.ch[i])
			return lhs.ch[i] - rhs.ch[i];
	}
	return 0;
}

bool StrCat(HString &lhs, HString &rhs)
{
	char*temp = new char[lhs.length + rhs.length];
	if(!temp) return false;

	for(int i = 0; i < lhs.length; ++i)
		temp[i] = lhs.ch[i];
	for(int i = 0; i < rhs.length; ++i)
		temp[lhs.length+i] = rhs.ch[i];

	if(lhs.ch) delete lhs.ch;
	lhs.ch = temp;
	lhs.length = lhs.length + rhs.length;

	return true;
}

void StrPrint(HString str)
{
	for(int i = 0; i < str.length; ++i)
		cout << str.ch[i];
	cout << endl;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值