用于案例特定排序的Java程序
给定一个由大写和小写字符组成的字符串S。任务是分别对大写和小写字母进行排序,这样如果原始字符串中的第 i 个位置有一个大写字符,那么它在排序后就不应该有小写字符,反之亦然。如下图所示:
插图:
Input : srbDKi
Output: birDKs
Processing : After sorting we have to place the lowercase characters to the lowercase and uppercase character to specific uppercase character
方法:
- 我们将使用两个ArrayList的一个小写值和第二存储来存储大写值。
- 将元素添加到列表中后,我们将使用Collections.sort(list) 方法对列表进行排序
- 排序后,我们将遍历字符串并检查 case-specific 并将元素存储在正确的位置
例子:
Java
// Java Program for Case Specific Sorting
// using Collections.sort(list) method
// Importing input output classes
// Importing utility classes
import java.io.*;
import java.util.*;
class GFG {
// Method 1
// To sort the string
static String sortString(String str)
{
// Creating two Arraylist class objects
// Declaring object of character type
ArrayList list = new ArrayList<>();
ArrayList list2 = new ArrayList<>();
// Initially the string is empty
String res = "";
// Iterating over the string
for (int i = 0; i < str.length(); i++) {
// Finding character at indexes
// using charAt() method in List object
if (str.charAt(i) >= 'a'
&& str.charAt(i) <= 'z')
list.add(str.charAt(i));
if (str.charAt(i) >= 'A'
&& str.charAt(i) <= 'Z')
list2.add(str.charAt(i));
}
// Sorting the Collection interface
// using sort() method
Collections.sort(list);
Collections.sort(list2);
int i = 0;
int j = 0;
// iterating over string using length() method
for (int k = 0; k < str.length(); k++) {
// If lowercase character encountered
if (str.charAt(k) >= 'a'
&& str.charAt(k) <= 'z') {
// Appending them all in beginning of string
res += list.get(i);
++i;
}
// If uppercase character encountered
else if (str.charAt(k) >= 'A'
&& str.charAt(k) <= 'Z') {
// Appending them all together after
// lowercase is finished in input string
res += list2.get(j);
++j;
}
}
return res;
}
// Method 2
// Main driver method
public static void main(String[] args)
{
// Passing the custom string as input for which we
// want case-specific sorting by calling the method
// 1 as defined above
System.out.println(sortString("defRTSersUXI"));
}
}
输出
deeIRSfrsTUX