比较包含格式化数据的字符串

compare strings containing formatted data

本文关键字:字符串 格式化数据 包含 比较      更新时间:2023-10-16

我正在研究这个项目,其中我有包含以下格式日期的字符串:str1-> "01/17/17" str2->"12/29/16"。我不允许使用任何转换函数,如atoi或stoi。我正在查看字符串的每个字符,并比较它们,看看哪个更少。如果str1的month = <= to str2,我将布尔数组设置为true。我显然错了。我想不出一个简单的解决方案,不涉及转换到不同的数据类型,但我不允许这样做。我非常感谢任何愿意帮助我的人。下面是我的代码:

sortData(items);
bool date[5];
date[0] = false;        //month
date[1] = true;         // '/'
date[2] = false;        //day
date[3] = true;         // '/'
date[4] = false;        //year
//looking for smallest string
string str1;
string str2;
for (int i = 4; i < 7; i++)
{
    str1 = items[i].date;
    str2 = items[i + 1].date;
    int size = str1.length();
    int count = 0;
    while (count < size)
    {
        if (str1[count] <= str2[count] || str1[count + 1] <= str2[count + 1])
        {
            date[0] = true;
        }
        //0,1  
        count=count+3;          //3,4
        if (str1[count] <= str2[count] || str1[count + 1] <= str2[count + 1])
            date[2] = true;     //day
        count = count + 3;
                //6,7
        if (str1[count] <= str2[count] || str1[count + 1] <= str2[count + 1])
            date[4] = true;
        count=count+1;
    }
}
int m = 0;      //for debugging

如果将字符串重新组织为yy/mm/dd,则可以使用字符串比较来查找哪个小于或大于或等于另一个。假设字符串总是2位数的格式,像这样的东西应该工作:

//This assumes mm/dd/yy
string FixString(string input)
{
    return input.substr(6) + "/" + input.substr(0, 5);
}
int main()
{
    string test = FixString("01/17/17");
    string test2 = FixString("12/29/16");
    bool test3 = test < test2;
    return 0;
}

这只是一个具有2个字符串日期的解决方案示例,它将比较年,然后是月,最后是日,因为优先级(年>月>日),在找到第一个之后,它将停止并打印最小的。

#include <iostream>
using namespace std;
int main()
{
    string str1 = "01/17/17";
    string str2 = "12/29/16";
    string smallest;
    for(int i=7; i >=0 ; i-=3)
    {
        if(str1[i-1] < str2[i-1])
        {
            smallest = str1;
            break;
        }
        else if(str1[i-1] > str2[i-1])
        {
            smallest = str2;
            break;
        }
        if(str1[i] < str2[i])
        {
            smallest = str1;
            break;
        }
        else if(str1[i] > str2[i])
        {
            smallest = str2;
            break;
        }
    }
    cout << smallest << endl;
    return 0;
}