Java程序排序字符串
在本文中,我们将了解如何对字符串进行排序。字符串是一种包含一个或多个字符并用双引号(“ ”)引起来的数据类型。字符串是一系列字符
以下是相同内容的演示 -
假设我们的输入是 -
Input string: javaprogram
所需输出应该是 -
String after sorting is: [a, a, a, g, j, m, o, p, r, r, v]
算法
Step 1 - START Step 2 - Declare a string value namely input_string, a character array charArray, char value name temp and an int value namely string_size. Step 3 - Define the values. Step 4 - Assign the string to the character array. Step 5 - Iterate over the elements of the character array twice, check if the adjacent elements are ordered, if not, swap them using temp variable. Step 6 - Display the sorted array Step 7 - Stop
示例 1
在这里,我们将 “main” 函数下所有操作绑定在一起。
import java.util.Arrays;
public class SortString {
public static void main(String args[]) {
int temp, string_size;
String input_string = "javaprogram";
System.out.println("The string is defined as: " +input_string);
char charArray[] = input_string.toCharArray();
string_size = charArray.length;
for(int i = 0; i < string_size; i++ ) {
for(int j = i+1; j < string_size; j++) {
if(charArray[i]>charArray[j]) {
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = (char) temp;
}
}
}
System.out.println("\nThe characters of the string after sorting is: "+Arrays.toString(charArray));
}
}输出
The string is defined as: javaprogram The characters of the string after sorting is: [a, a, a, g, j, m, o, p, r, r, v]
示例 2
在这里,我们将操作封装到表现对象面向编程的函数中。
import java.util.Arrays;
public class SortString {
static void sort(String input_string){
int temp, string_size;
char charArray[] = input_string.toCharArray();
string_size = charArray.length;
for(int i = 0; i < string_size; i++ ) {
for(int j = i+1; j < string_size; j++) {
if(charArray[i]>charArray[j]) {
temp = charArray[i];
charArray[i] = charArray[j];
charArray[j] = (char) temp;
}
}
}
System.out.println("\nThe characters of the string after sorting is: "+Arrays.toString(charArray));
}
public static void main(String args[]) {
String input_string = "javaprogram";
System.out.println("The string is defined as: " +input_string);
sort(input_string);
}
}输出
The string is defined as: javaprogram The characters of the string after sorting is: [a, a, a, g, j, m, o, p, r, r, v]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP