将数组中的大写字母与小写字母分开

:一个数组总存储有且in有大写和小写字母,编写一个函数对数组内的字母重新排列,让小写字母在所有大写字母之前。(相对顺序没有要求)【2012·中兴、2013·腾讯】

使用快排的一次排列即可实现,代码如下:

 1 #include <iostream>
 2 #include <string>
 3 #include <vector>
 4 using namespace std;
 5 
 6 bool isUpper( char ch ) //equal isupper()
 7 {
 8     if( ch >='A' && ch <= 'Z')
 9         return true;
10     return false;
11 }
12 
13 bool isLower( char ch )//equal islower()
14 {
15     if( ch >= 'a' && ch <= 'z')
16         return true;
17     return false;
18 }
19 
20 void Partition(string &arr, int len) //快排的一次排序过程
21 {
22     if( len <= 1)
23         return;
24 
25     int low = 0;
26     int high = len-1;
27 
28     while( low < high)
29     {
30         while( low < high && isUpper(arr[high]) ) --high; //如果是大写字母,位置向前移动
31         while( low < high && isLower(arr[low]) ) ++low; //如果是小写字母,位置向后移动
32         char tmp = arr[low]; //交换
33         arr[low] = arr[high];
34         arr[high] = tmp;
35     }
36 }
37 
38 int main(int argc, char const *argv[])
39 {
40     string  str= "HElloWorlDThanKYOU";
41     cout <<"Before: "<< str << endl;;
42 
43     Partition( str, str.size() );
44     cout <<"After : "<< str << endl;
45     return 0;
46 }
View Code

相关文章: