字符串整理问题(编了好多程序,这个程序难住了,请高手指点一下!)
将形如 A4A2Z9Q7Q5A3B3B4A7 的字符串,整理成形如 A2-4A7B3-4Q5Q7Z9 的字符串。整理规则:如果有若干个对的字母相同,且数字是连续的,例如有A1B2A2A4A3字符串,其中A1,A2,A3,A4,四对的字母相同,并且数字是连续的,可以将其合并,即在此字母后用'-'标出数字的范围,例如上述四对可以合并成A1-4。然后再以字母为主序,以数字为次序进行了升序排序。
程序代码:#include "stdafx.h"
#include "ctype.h"
struct obj1
{
int i;
obj1 *next;
};
struct obj2
{
char a;
obj1 * head;
};
void AddNumber(obj2* obj, char num)
{
if(isdigit(num))
{
int n = num-'0';
obj1 *last = NULL;
obj1 *next = obj->head;
while(next!=NULL)
{
if(next->i==n)
return;
if(next->i > n)
{
break;
}
last = next;
next = next->next;
}
obj1 *oo = new obj1();
oo->i = n;
oo->next = next;
if(obj->head==NULL || last==NULL)
{
obj->head = oo;
}
else
{
last->next = oo;
}
}
}
void Display(char a, obj1 *oo)
{
int n = oo->i;
int n2 = n;
while(oo->next!=NULL)
{
if(oo->next->i!=n2+1)
break;
oo = oo->next;
n2 = oo->i;
}
if(n==n2)
{
printf("%c%d",a,n);
}
else
{
printf("%c%d-%d",a,n,n2);
}
if(oo->next!=NULL)
{
Display(a, oo->next);
}
}
void Process(char *str)
{
const int MAX=26;
obj2 data[MAX];
int i, j;
for(i=0;i<MAX;i++)
{
data[i].a = 'A'+i;
data[i].head = NULL;
}
for(i=0;str[i]!=0 && str[i+1]!=0;i+=2)
{
for(j=0;j<MAX;j++)
{
if(data[j].a==str[i])
{
AddNumber(data+j, str[i+1]);
}
}
}
for(i=0;i<MAX;i++)
{
if(data[i].head!=NULL)
{
Display(data[i].a, data[i].head);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
Process("A4A2Z9Q7Q5A3B3B4A7");
return 0;
}