12.30

字符串排序

题目内容:

有5个字符串,首先将它们按照字符串中字符个数由小到大排序,再分别取出每个字符串的第三个字母合并成一个新的字符串输出(若少于三个字符的输出空格)。要求:利用字符串指针和指针数组实现。

输入格式:

5个字符串,用回车分隔

输出格式:

输出一个字符串:按5个字符串中字符个数由小到大排序,每个字符串后面有一个空格;再分别取出每个字符串的第三个字母合并成一个新的字符串输出,若少于三个字符的输出空格

输入样例:

test1234

123test

cumt

think

apples

 

输出样例:

cumt think apples 123test test1234

concatenate string:mip3s

自己用string写的:

 1 #include<string>
 2 using namespace std;
 3 int main()
 4 {
 5 string p[5];
 6 string box;
 7 char a[5];
 8 int i,j;
 9 for(i=0;i<5;i++)
10 cin>>p[i];
11 for(i=4;i>0;i--)
12 {
13 for(j=0;j<i;j++)
14 {
15 if(p[j+1].size()<p[j].size()) 
16 {
17     box=p[j];
18     p[j]=p[j+1];
19     p[j+1]=box;
20     }    
21 }
22 }
23 for(i=0;i<5;i++)
24 cout<<p[i]<<" ";
25 cout<<endl<<"concatenate string:";
26 for(i=0;i<5;i++)
27 {
28 if(p[i][2]=='\0') cout<<" ";
29 else cout<<p[i][2];
30 }
31 }

别人用char*写的:

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 int main()
 5 {
 6     char* s[5] = {};
 7     char* temp = {};
 8     int i, j;
 9     for (i = 0; i < 5; i++)
10     {
11         s[i] = new char[50];
12         cin >> s[i];
13     }
14     for (i = 0; i < 4; i++)
15     {
16         for (j = 0; j < 4 - i; j++)
17         {
18             if (strlen(s[j]) > strlen(s[j + 1]))
19             {
20                 temp = s[j];
21                 s[j] = s[j + 1];
22                 s[j + 1] = temp;
23             }
24         }
25     }
26     for (i = 0; i < 5; i++)
27         cout << s[i] << ' ';
28     cout << endl;
29     cout << "concatenate string:";
30     for (i = 0; i < 5; i++)
31     {
32         if (strlen(s[i]) < 3)
33             cout << ' ';
34         else
35             cout << s[i][2];
36     }
37     
38     return 0;
39 }

要点:字符串数组

posted @ 2021-12-30 22:41  闻淤野  阅读(122)  评论(0)    收藏  举报