帮助!这里我有一个程序,按字母顺序对输入字符串进行排序。问题是它单独对输入的字符串进行排序,但我需要将它们合并并排序在一起。我做错了什么?
int main (void)
{
char repeat;
do{
char string[128], string1[128], temp;
int n, i, j;
cout<<"\nEnter symbols: "<<endl;
gets(string);
n = strlen(string);
for (i=0; i<n-1; i++)
{
for (j=i+1; j<n; j++)
{
int s = tolower(string[i]) - tolower(string[j]);
if ( s == 0 )
{
s = string[i] - string[j];
}
if (s > 0)
{
temp = string[i];
string[i] = string[j];
string[j] = temp;
}
}
}
cout<<"\nSorted alphabetically: "<<endl;
printf("\n%s", string);
printf("\n");
cout<<"\nEnter more symbols: "<<endl;
gets(string1);
n = strlen(string1);
for (i=0; i<n-1; i++)
{
for (j=i+1; j<n; j++)
{
int s = tolower(string1[i]) - tolower(string1[j]);
if ( s == 0 )
{
s = string1[i] - string1[j];
}
if (s > 0)
{
temp = string1[i];
string1[i] = string1[j];
string1[j] = temp;
}
}
}
cout<<"\nSorted alphabetically: "<<endl;
下面的函数合并了字符串,当它们都已经排序时
strcat(string, string1);
printf(\n%s", string);
printf("\n");
cout << "To repeat press j" << endl;
cin >> repeat;
}
while ( repeat == 'j' );
system("Pause");
return 0;
}
答案 0 :(得分:0)
最简单的方法是将字符串合并为一个新字符串。
int main (void)
{
char repeat;
do{
char string[128], string1[128],string2[256], temp;
int n, i, j;
cout<<"\nEnter symbols: "<<endl;
gets(string);
cout<<"\nEnter more symbols: "<<endl;
gets(string1);
strcpy (string2,string);
strcat (string2,string1);
// rest of your code here. You only need to sort string2