2016-11-05 33 views
-2

我正在处理这个项目,其中包含以下格式的日期的字符串: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 
+0

没有输入/输出示例,也没有错误?好的char'0'比char'1'要小,以此类推,因为只有一天,一个月和一年,做一段时间是无稽之谈,只是比较优先级(年 - >月 - >日) – cpatricio

回答

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; 
} 
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; 
}