比较包含格式化数据的字符串
compare strings containing formatted data
我正在研究这个项目,其中我有包含以下格式日期的字符串: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;
}
相关文章:
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 如何在C++中对静态缓冲区执行字符串格式化?
- 为什么C++不允许我在类中使用字符串作为数据成员?
- 标准地图如何知道使用标准字符串的数据作为键
- 链接列表(C )中(字符串)数据的用户输入
- 用C++读取带多个分隔符的格式化数据
- 使用c++只读取已格式化和未格式化数据的文件中的已格式化数据
- MySQL UDF返回字符串与数据重叠
- WXSTRING:是否有使用类似Python3的占位符实现字符串格式化的C/C 代码
- 我可以告诉解决方案如何使用 C 写入此格式化数据
- C字符串.格式化插入斜杠
- 使用 cpp/c++ 中的字符串值数据声明变量名称
- 如何截断字符串 [格式化] ?C++
- C++ 中双引号内的字符串的数据类型是什么
- 对齐包含字符串的数据
- 如何将返回类型字符串的数据复制到C++中
- 将格式化数据转换为结构的方便方法
- 比较包含格式化数据的字符串
- c++字符串附加格式化数据