This article describes the Java implementation of sorting numerical values in strings. Share it for your reference, as follows:
question:
Sort the values in the string "34 9 -7 12 67 25" from small to large!
Solution:
First introduce a few eclipse shortcut keys: enter for and then press " alt+/ " to quickly write a for loop
Select a lowercase word Ctrl+Shift+x variable uppercase, select a lowercase word Ctrl+Shift+y variable lowercase
Please see the specific implementation code below:
import java.util.Arrays;public class Main_4 { private static String SPACE=" "; public static void main(String[] args) { /* * Comprehensive exercises: * Sort the values in this string from small to large in size*/ String str="34 9 -7 12 67 25"; str=sortStringNumber(str); System.out.println(str); } private static String sortStringNumber(String str) { // 1 Cut the values in the string through certain rules to obtain the string array String[] str_nums=toStringArray(str); // 2 Convert the string array into an int array int[] nums=toIntArray(str_nums); // 3 Sort the int array sortIntArray(nums); // 4 Turn the int array into a string return ArrayToString(nums); } /* * Turn the int array into a string*/ private static String ArrayToString(int[] nums) { // 1 Create a string buffer StringBuilder sb=new StringBuilder(); for (int i = 0; i < nums.length; i++) { if(i!=nums.length-1) sb.append(nums[i]+SPACE); else sb.append(nums[i]); } return sb.toString(); } /* * Sort the int array*/ private static void sortIntArray(int[] nums) { Arrays.sort(nums); } /* * Convert a string array into an int array*/ private static int[] toIntArray(String[] str_nums) { // Define an int array int[] arr=new int[str_nums.length]; // traverse the string array for (int i = 0; i < arr.length; i++) { // Convert the array-formatted string into an integer and store it in the arr array arr[i]=Integer.parseInt(str_nums[i]); } return arr; } /* * Convert the string to a string array*/ private static String[] toStringArray(String str) { return str.split(SPACE); }}Running results:
PS: Here is a demonstration tool for your reference:
Online animation demonstration insert/select/bubble/merge/hill/quick sorting algorithm process tool:
http://tools.VeVB.COM/aideddesign/paixu_ys
For more information about Java algorithms, readers who are interested in this site can view the topics: "Java Data Structure and Algorithm Tutorial", "Summary of Java Operation DOM Node Tips", "Summary of Java File and Directory Operation Tips" and "Summary of Java Cache Operation Tips"
I hope this article will be helpful to everyone's Java programming.