我觉得我的function
不必要地长,但是我不知道如何在不添加库的情况下减少长度(不允许添加额外的库)。我正在创建一个String类,它的行为应类似于 c ++ string
。我还包括了constructors
,使我的代码更易于理解。我曾尝试使用while(true)loop
,但是当我创建它时,它的长度几乎与此相同。
String::String() :len(0), str(nullptr)
{}
String::String(const char arr[])
{
len = get_cstr_length(arr);
str = new char[len];
for (int j = 0; j < len; j++)
{
str[j] = arr[j];
}
}
int compare_strings(const String &obj1, const String &obj2)
{
int count = 0;
int len1 = obj1.length();
int len2 = obj2.length();
if (len1 != 0 && len2 != 0)
{
if (len1 < len2)
{
for (int i = 0; i < len1; i++)
{
if (obj1[i] > obj2[i])
return 1;
else if (obj1[i] < obj2[i])
return -1;
else
count++;
}
if (count == len1)
return -1;
}
else
{
for (int i = 0; i < len2; i++)
{
if (obj1[i] > obj2[i])
return 1;
else if (obj1[i] < obj2[i])
return -1;
else
count++;
}
if (count == len2 && len1 != len2)
return 1;
else
return 0;
}
}
else
{
if (len1 == 0 && len2 == 0)
return 0;
else if (len1 == 0 && len2 != 0)
return -1;
else
return 1;
}
}
答案 0 :(得分:0)
您不需要提前检查长度:
int compare_strings(const String &obj1, const String &obj2)
{
int len1 = obj1.length();
int len2 = obj2.length();
int prefix = min(len1, len2);
// compare the strings up to the length of the shorter string
for (int i = 0; i < prefix; i++)
{
if (obj1[i] > obj2[i])
return 1;
else if (obj1[i] < obj2[i])
return -1;
}
// no need for separate count variable, i must equal prefix
if (len1 < len2)
{
return -1;
}
if (len2 < len1)
{
return 1;
}
return 0;
}