创建字符串数据结构

时间:2018-02-07 04:46:17

标签: c++ arrays string class data-structures

我对我的String类赋值感到非常困惑。我基本上是在创建一个字符串数据结构,但没有使用string data type。它需要三个数据成员:值,长度和容量。我做了那些。

#pragma once
#include <iostream>
#include <string>
using namespace std;

class Str {
    private:
    int length;
    int capacity;
    char* value;

此外还有8类方法:grow,min,difference,getCharArrSize,copy,concatenate,compare和print。 我获得了成长,分钟,差异和GetCharArrSize。它们看起来像这样

void grow() {
    char *temp = value;
    capacity *= 2;
    value = new char[capacity];
    for (int i = 0; i < length; i++) {
        value[i] = temp[i];
    }
}

int min(int a, int b) {
    if (a < b) return a;
    else return b;
}

int diffrence(int a, int b) {
    int d = 0;
    if (a > b) d = a - b;
    else if (b > a) d = b - a;
    return d;
}

int getCharArrSize(char *v) {
    int c = 0;
    while (v[c] != '\0') {
        c++;
    }
    return c;
}

现在说明增长用于复制和连接。那会怎么样?复制指令是:覆盖字符串的数据 包含s中包含的数据的数组。 对于连接是:将s内的数据追加到 存储在字符串中的数据。 我也在头文件中做了这一切。测试文件如下所示:

#pragma once
#include "NewString.h"
#include <iostream>
#include <string>
using namespace std;

int main() {
    Str s1("Hello ");
    Str s2("World");
    Str s3(", My ");
    Str s4("Name ");
    Str s5("is ");
    Str s6("Chad!");
    cout << s1.size() << endl;
    Str s7;
    s7.copy(s1);
    s7.concatenate(s2);
    s7.concatenate(s3);
    s7.concatenate(s4);
    s7.concatenate(s5);
    s7.concatenate(s6);*/
    s7.print();
    cout << "\n\n";
    Str s8("Hello World, My Name is Chad!");
    if (s8.compare(s7) == 0) {
        cout << "They Match!" << endl;
    }
    Str s9("I dont match....");
    if (s9.compare(s8) != 0) {
        cout << "I differ by " << s9.compare(s8) << " characters..." <<
            endl;*/
    }
}

我很困惑,不知道如何继续。 请帮助我。 在此先感谢

1 个答案:

答案 0 :(得分:1)

首先让我们看一下grow()的作用:

void grow() {
    char *temp = value; 
    capacity *= 2;
    value = new char[capacity]; // Double capacity
    for (int i = 0; i < length; i++) {
        value[i] = temp[i]; // Copy all data from temp into value
    }
}

因此,例如,如果之前的临时值为['a', 'b', 'c'],则现在为['a', 'b', 'c', '', '', '']。有意义吗?

现在的问题是:如何帮助我们复制和连接? 让我们从复制开始。我们需要能够将参数中的字符串复制到调用该方法的字符串中。例如,在致电str1.copy(str2)后,str1应与str2相同。但问题出在这里:如果str2的容量大于str1的容量怎么办?我们不能简单地将str2的内容复制到str1,因为它们不适合。所以:我们使用grow()方法直到它足够大。

void copy(const Str& other) {
    // Grow buffer
    while (this.capacity < other.capacity) {
        this.grow();
    }

    // Copy contents of other
    for (int charIndex = 0; charIndex < other.capacity; charIndex++) {
        this.value[charIndex] = other.value[charIndex]
    }
}

现在,我们可以轻松地将此知识扩展到concatenate:我们希望将str2添加到str1,但str1还不够大。要解决此问题,我们会调用grow(),直到我们大于或等于str1.capacity + str2.capacity,然后将str2的内容复制到str1的末尾。

干杯,祝你好运!