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

时间:2016-11-05 04:30:45

标签: c++ string

我正在处理这个项目,我的字符串包含以下格式的日期:str1-> “01/17/17”str2->“12/29/16”。 我不允许使用任何转换功能,如atoi或stoi。 我正在查看字符串的每个字符并比较它们以查看哪个字符串更少。如果str1的月份是< =到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

2 个答案:

答案 0 :(得分:1)

如果将字符串重新组织为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;
}

答案 1 :(得分:0)

这只是一个包含2个字符串日期的解决方案示例,它将比较年份,月份和最后一天,因为优先级(年份&gt;月份&gt;日期),找到第一个后,它将停止并打印最小的。

#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;
}
相关问题