字符串處理。。題目就不介紹了。應該是一道比較水的題,思路很簡單,就是排個序。
但是有很多細節要注意,也很考驗一些基本功。
1.注意字母排序時是不區分大小寫的。本來想用現成的sort,但是處理二維數組,並且還要忽略大小寫,本弱菜不知道該怎麼寫了。最後放棄sort,自己寫了一個對字符串進行排序的strsort。最樸素的n^2的排序。。還好最後沒超時。
2.對於數字,可以用atoi這個函數。
atoi()會掃描參數nptr字符串,檢測到第一個數字或正負符號時開始做類型轉換,之後檢測到非數字或結束符 \0 時停止轉換,返回整型數。
然後直接sort即可。
3.我用了一個bool types[]記錄哪個位置應該出數字還是單詞
4.注意輸出的時候逗號,句號及空格的安排。
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <stack>
#include <memory.h>
using namespace std;
char str0[105][100];
int str1[105];
bool types[205];
int l0;
int num0,num1;
bool cmp0(char a[],char b[])
{
int i;
for(i=0; i<strlen(a); i++)
if(a[i]>='A'&&a[i]<='Z') a[i]=a[i]+32;
for(i=0; i<strlen(b); i++)
if(b[i]>='A'&&b[i]<='Z') b[i]=b[i]+32;
if(strcmp(a,b)>0) return 1;
else return 0;
}
void strsort()
{
int i,j;
for(i=0;i<num0;i++)
for(j=0;j<num0;j++)
{
char b1[1000],b2[1000];
strcpy(b1,str0[i]);
strcpy(b2,str0[j]);
if(!cmp0(b1,b2))
{
char t[1000];
strcpy(t,str0[i]);
strcpy(str0[i],str0[j]);
strcpy(str0[j],t);
}
}
}
int main()
{
while(1)
{
num0=0;
num1=0;
memset(types,0,sizeof(types));
char temp[100];
int i=0;
while(1)
{
scanf("%s",temp);
if((temp[0]>='0'&&temp[0]<='9')||temp[0]=='-') //注意負數的情況
{
types[i]=1;
str1[num1++]=atoi(temp);
}
else
{
types[i]=0;
strcpy(str0[num0++],temp);
}
i++;
int l=strlen(temp);
if((temp[l-1])=='.')break;
}
if(strcmp(temp,".")==0)break;
strsort();
sort(str1,str1+num1);
int counter0=0;
int counter1=0;
for(int i=0;; i++)
{
if(types[i]==0)
{
if(counter0==num0)continue;
str0[counter0][strlen(str0[counter0])-1]='\0'; //把單詞最後的那個逗號給去掉
printf("%s",str0[counter0++]);
}
else
{
if(counter1==num1)continue;
printf("%d",str1[counter1++]);
}
if(counter0==num0&&counter1==num1)
{
printf(".\n");
break;
}
printf(", ");
}
}
return 0;
}