【问题标题】:Char pointer objects and respective char array element comparisonsChar 指针对象和各自的 char 数组元素比较
【发布时间】:2018-02-04 22:47:29
【问题描述】:

我正在用多种方法编写我的自定义字符串类。问题是比较方法不能按我的意愿工作。当两个 char 数组不同时,而不是什么都不做,一个 if 条件仍然在我的 main 函数中进行。

当我使用 g++ 编译时没有给出错误。该代码在语法上是正确的,但在逻辑上是错误的。我知道这一点,因为我可以为比较方法提供两个内容不同的字符数组,它们是否以这种方式不同并不重要,因为主函数将为“s8.compare(s7) == 1”运行 if 条件不管 compare 方法中的结果是否为真。

我将在下面发布整个代码。任何帮助是极大的赞赏。

字符串.h

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

    //Doubles the size of the string when called.
void growArray();

    //If the two strings are uneven, get absolute value of difference in length.
    int difference(int a, int b);

    //Calculates the size of a character array, passed in as an argument
    int getCharArrSize(const char *v);



public:
    Str();
    explicit Str(const char *STR);
    void copy(Str s);
    void concatenate(Str s);
    bool compare(Str s);
    void print();
};



//Str constructor
Str::Str() {

    //Assign value, capacity, and length to any new Str object
    value = new char[100];
    capacity = 100;
    length = 0;
}

//Pass STR object as a pointer to string object constructor
Str::Str(const char *STR) {

    length = getCharArrSize(STR);
    capacity = 100;

    value = new char[capacity];

    //Copy contents from STR to string object
    for (int i = 0; i < length; i++)
        value[i] = STR[i];
}

//Doubles the size of the string when called.
void Str::growArray() {
    const char *tmp = value;
    capacity *= 2;
    value = new char[capacity];

    for (int i = 0; i < length; i++)
        value[i] = tmp[i];
}

//If the two strings are uneven, get absolute value of difference in length.
int Str::difference(int a, int b) {
    int d = 0;
    if (a > b) d = a - b;
    else if (b > a) d = b - a;
    return d;
}


//Calculates the size of a character array, passed in as an argument
int Str::getCharArrSize(const char *v) {
    int c = 0;
    while (v[c] != '\0') {
        c++;
    }
    return c;
}

//Overwrites the data of the string array with the data contained in s
void Str::copy(Str s) {

    //Check ability for empty string object to hold Str s contents
    if (capacity > s.length) {

        //Copy over each element until s length is reached
        for (int i = 0; i < s.length ; i++)
            value[i] = s.value[i];

        //Set string object length to copy's size
        length = getCharArrSize(value);

    } else { growArray(); }
}

//Concatenate Str s onto string object
void Str::concatenate(Str s) {

    //Check ability for string object to hold itself and concatenated chars
    if (capacity > length + s.length) {

        //Fill string object with s object until end of combined lengths if necessary
        for (int i = 0; i < length + s.length; i++)
            value[length + i] = s.value[i];

        //Set length based on chars in concatenated string object
        length = getCharArrSize(value);

    } else { growArray(); }
}




//Compare each element in Str s against string for similarities
bool Str::compare(Str s) {

    if (length == s.length) {

        if (*value == *s.value) {

            while ((*value != value[length]) && (*s.value != s.value[s.length])) {

                value++;
                s.value++;

            }
            return true;
        } else return false;
    } else {
        difference(length, s.length);
    }
}




//Print function
void Str::print() {
    std::cout << value << std::endl;
}

main.cpp

#include"string.h"

int main() {
    Str s1("Hello ");
    Str s2("World");
    Str s3(", my ");
    Str s4("Name ");
    Str s5("is ");
    Str s6("Chad!");

Str s7;
    s7.copy(s1);
    s7.concatenate(s2);
    s7.concatenate(s3);
    s7.concatenate(s4);
    s7.concatenate(s5);
    s7.concatenate(s6);

    s7.print();

    std::cout << "\n\n";

    Str s8("Hello World, My Name is Chad!");

    if (s8.compare(s7) == 1) {
        std::cout << "They Match!" << std::endl;
    }

    Str s9("I dont match....");

    if (s9.compare(s8) == 0) {
        std::cout << "I differ by " << s8.compare(s6) << " characters" << std::endl;
    }
}

上面的代码返回的结果看起来正确,但是将 (s8.compare(s7) == 1) 更改为 (s8.compare(s5) == 1) 会返回“它们匹配!”当我试图检查 char 数组中的每个单独元素时,只有当它们的长度相同并且每个字符在数组中匹配时才返回 true。

【问题讨论】:

    标签: c++ arrays char


    【解决方案1】:

    您的程序具有未定义的行为,因为 Str::compare 在其中一个分支中没有 return 语句。

    bool Str::compare(Str s) {
    
        if (length == s.length) {
         ...
        } else {
    
            // Missing return statement.
            difference(length, s.length);
        }
    }
    

    也许您想将该行更改为:

            return (difference(length, s.length) == 0);
    

    【讨论】:

    • 我不想在那里返回零,因为这是我对长度不相等的检查。如果它们不相等,我想运行差异方法,它给出了数组不同的元素数量。
    • @Biorecepto, difference 确实有一个return,但使用difference(length. s.length); 不会从compare 返回该值。您必须在此处明确使用 return 关键字。
    【解决方案2】:

    您的循环在没有比较的情况下运行。您比较 char 数组中的初始值,然后遍历其余部分而不进行比较。所以每次初始值相等时都会返回true。

    在确定相同长度后循环运行,然后比较每个字符。如果它们不相等,则该函数将返回 false。否则该函数将返回 true。

    bool Str::compare(Str s) {
        if (length == s.length) {
            while ((*value != value[length]) && (*s.value != s.value[s.length])) {
                if (*value == *s.value) {
                      value++;
                      s.value++;
                } else { 
                      return false;//will return false as soon as a comparison is false
                }
            }
            return true;
        } else {
            difference(length, s.length);
        }
     }
    

    您还需要从差异函数返回一个布尔值。如果您想从该函数返回整数,请切换到比较函数上的整数返回,并使用 0 和 1 作为它们的布尔对应项。

    【讨论】:

    • 我保持数据类型相同,但是我为您提出的第一点进行了编辑。 'difference' 方法返回一个 int,因为我想返回数组不同的数量。从差异函数返回布尔值不会实现这一点。
    • 我的意思是将比较函数的返回类型更改为 int。然后所有可能的分支都返回相同的类型。
    猜你喜欢
    • 2019-09-13
    • 2015-07-28
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多