一道简单的c++题,好像要用到类,求大佬解答
一道简单的c++题,好像要用到类,求大佬解答Pleaseusetheobject-orientedmethod,designa'SString'classbycharac...
一道简单的c++题,好像要用到类,求大佬解答Please use the object-oriented method,design a 'SString' class by character array or other forms , instead of 'string (S) in the standard library, need to be able to achieve:return the length of the string,splice the string,change a specified character in the string,search by index and so on(the more the better).Test it in the main function.
展开
1个回答
展开全部
//SString.h
#pragma once
#include<iostream>
class SString {
private:
unsigned size;
unsigned capacity;
char *array;
public:
SString();
SString(char *init);
~SString();
unsigned getSize()const {
return size;
}
unsigned getCapacity()const {
return capacity;
}
void setChar(unsigned index, char c);
char getChar(unsigned index) const;
unsigned searchChar(char c) const;
void splice(unsigned index, unsigned number);
void append(char c);
void shrink();
void extendTo(unsigned capacity);
SString& operator+(SString& ss);
};
std::ostream& operator<<(std::ostream &os, const SString& ss);
//SString.cpp
#include"带敬灶SString.h"
#include<cstring>
#include<stdexcept>
SString::SString() :size(0), capacity(0),array(nullptr) {}
SString::SString(char *init) {
蠢扮 size = strlen(init);
capacity = 2 * size;
array = new char[capacity];
memcpy(array, init, size);
}
SString::~SString() {
delete[] array;
}
void SString::setChar(unsigned index, char c) {
if (index >= size)throw std::runtime_error("Index Out Of Range");
array[index] = c;
}
char SString::getChar(unsigned index)const {
if (index >= size)throw std::runtime_error("Index Out Of Range");
return array[index];
}
unsigned SString::searchChar(char c) const {
for (unsigned i = 0; i < size; ++i) {
if 稿尺(array[i] == c)return i;
}
throw std::runtime_error("Char Not Found");
}
void SString::splice(unsigned index, unsigned number) {
unsigned nextpart = index + number;
if (nextpart >= size) {
size = index + 1;
}
else {
while (nextpart < size)
array[index++] = array[nextpart++];
size -= number;
}
}
void SString::append(char c)
{
if (size == capacity) {
capacity = 2*capacity+1;
char *array2 = new char[capacity];
memcpy(array2, array, size);
delete[] array;
array = array2;
}
array[size++] = c;
}
void SString::shrink() {
capacity = size;
char *array2 = new char[capacity];
memcpy(array2, array, size);
delete[] array;
array = array2;
}
void SString::extendTo(unsigned capacity) {
if (this->capacity< capacity) {
char *array2 = new char[capacity];
memcpy(array2, array, size);
delete[] array;
array = array2;
this->capacity = capacity;
}
}
SString& SString::operator+(SString& ss) {
if (capacity < size + ss.size) {
extendTo(size + ss.size);
}
memcpy(array+size, ss.array, ss.size);
size += ss.size;
return *this;
}
std::ostream& operator<<(std::ostream &os, const SString& ss) {
for (unsigned i = 0; i < ss.getSize(); ++i)
os << ss.getChar(i);
return os;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询