一道面试测试题
两个字符串(字符串1、字符串2)的大小比较,字符串可能既含有字符(a~z)又含有数字(0~9)。
比较规则:
(1)从左到右分离单纯的子字符串(全字符)和子数字串(全数字)进行比较。
(2)如果被比较的都是子字符串,则可以调用strcmp比较子字符串大小。
(3)如果被比较的都是子数字串,则根据值比较大小,如果值相等,则子数字串短的一方大(前面的0少)。
(4)如果被比较的一边是子数字串,一边是子字符串,则子字符串大。
写一个int MyCompareText(char *p1, char *p2)函数,不能用递归,符合上面条件,并用一个测试程序,测试这个函数。
测试例子,A1,A01,A2,A11大小顺序将是A01,A1,A2,A11。
写完程序后,请写出正常态和异常态的test case,做成一份测试报告。
[解决办法]
这个问题,曾经有人问过了。
给你个狠的
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string>
#include <map>
using namespace std;
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/tuple/tuple_io.hpp>
#include <boost/tuple/tuple_comparison.hpp>
using namespace boost;
int main(void)
{
typedef tuple <string, int, int> KEY;
typedef vector <KEY> KEYS;
typedef multimap <KEYS, string> RESULT;
string ss[] = { "b01 ", "b1 ", "b11 ", "b2 ", "a1 ", "1a "};
RESULT r;
for (string * s = ss; s != ss + sizeof(ss) / sizeof(ss[0]); ++s)
{
KEYS temp;
for (sregex_iterator iter(s-> begin(), s-> end(), regex( "(\\d+)|([[:alpha:]]+) ")); iter != sregex_iterator(); ++iter)
{
temp.push_back(make_tuple(iter-> str(2), iter-> length(1) ? lexical_cast <int> (iter-> str(1)) : 0, -iter-> length(1)));
}
r.insert(make_pair(temp, *s));
}
for (RESULT::iterator iter = r.begin(); iter != r.end(); ++iter)
{
cout < < iter-> second < < " ";
}
system( "pause ");
return 0;
}