创建字符串数据串起

Creating a String Data Stucture

本文关键字:数据 字符串 创建      更新时间:2023-10-16

我对我的字符串类分配非常困惑。我基本上是在制作字符串数据结构,但不使用string data type。它需要三个数据成员:价值,长度和容量。我做了。

#pragma once
#include <iostream>
#include <string>
using namespace std;
class Str {
    private:
    int length;
    int capacity;
    char* value;

还假设有8个类方法:成长,最小,差异,getchararrsize,coppy,concatenate,concateNate,concare和Print和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] != '') {
        c++;
    }
    return c;
}

现在,指示说生长用于复制和连接酸盐。那将如何工作?复制的说明是:覆盖字符串的数据带有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 << "nn";
    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;*/
    }
}

我很困惑,不知道该如何进行。请帮助我。预先感谢

所以让我们开始查看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的末尾。

欢呼和好运!