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