Dark Horse Programmer (Java) common class for----API (advanced operation of arrays, regular expressions)

Source: Internet
Author: User
Tags sorts


------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! ------- advanced operation of the 4.7 array 4.7.1 Sort 1. Bubble sort

Adjacent elements 22 comparison, large back, the first time, the maximum value appears at the maximum index.

Import Java.awt.image.bufferstrategy;public class ArrayDemo2 {public static void main (string[] args) {//define an array int[] arr = {24, 69, 80, 57, 13}; System.out.println ("Pre-sort:");p Rintarray (arr); Bubblesort (arr); System.out.println ("After sorting:");p Rintarray (arr);} Bubble sort public static void Bubblesort (int[] arr) {for (int x = 0;x<arr.length-1;x++) {for (int y = 0;y<arr.length-1-x;y+ +) {if (arr[y]>arr[y+1]) {int temp = Arr[y];arr[y] = arr[y+1];arr[y+1] = temp;}}} Traverse function public static void PrintArray (int[] arr) {System.out.print ("["); for (int x=0;x<arr.length;x++) {if (x== arr.length-1) {System.out.print (arr[x]);} Else{system.out.print (arr[x]+ "");}} System.out.println ("]");}}

Operation Result:


2. Select Sort

Starting with the 0 index, and then comparing the following elements, small forward, the first time, the minimum value appears at the minimum index.

public class ArrayDemo2 {public static void main (string[] args) {//define an array int[] arr = {24, 69, 80, 57, 13}; System.out.println ("Pre-sort:");p Rintarray (arr); Selectsort (arr); System.out.println ("After sorting:");p Rintarray (arr);} Select sort public static void Selectsort (int[] arr) {for (int x = 0; x < arr.length-1; + +) {for (int y = x; y < ARR.L Ength-1; y++) {if (Arr[x] > arr[y + 1]) {int temp = arr[x];arr[x] = arr[y + 1];arr[y + 1] = temp;}}} Traverse function public static void PrintArray (int[] arr) {System.out.print ("["); for (int x = 0; x < arr.length; X + +) {if (x = = arr.length-1) {System.out.print (arr[x]),} else {System.out.print (arr[x] + ",");}} System.out.println ("]");}}

Operation Result:


Exercise: Sort the characters in a string. "DACGEBF"--"ABCDEFG"

public class Arraytest {public static void main (string[] args) {String s = "DACGEBF"; char[] CHS = S.tochararray ();//BUBBL Esort (CHS); Selectsort (CHS); s = string.valueof (CHS); System.out.println (s);} Bubble sort public static void Bubblesort (char[] CHS) {for (int x = 0; x < chs.length-1; + +) {for (int y = 0; y < chs. Length-1-X; y++) {if (Chs[y] > chs[y + 1]) {Char temp = chs[y];chs[y] = chs[y + 1];chs[y + 1] = temp;}}} Select sort public static void Selectsort (char[] CHS) {for (int x = 0; x < chs.length-1; + +) {for (int y = x; y < chs. Length-1; y++) {if (Chs[x] > chs[y + 1]) {Char temp = chs[x];chs[x] = chs[y + 1];chs[y + 1] = temp;}}}}

Operation Result:


4.7.22-Point lookup (for ordered arrays)

public class Arraydemo {public static void main (string[] args) {//define an array int[] arr = {11,22,33,44,55,66,77};//write function implementation int Inde x = GetIndex (arr, 33); System.out.println ("index:" +index);//What happens if this element does not exist? index = GetIndex (arr, 333); System.out.println ("index:" +index);  /* * Two explicit: * return value type: int * parameter list: int[] arr,int value */public static int getindex (int[] arr,int value) {//define maximum index, minimum index int max = Arr.length-1;int min = 0;//calculates the intermediate index int mid = (max +min)/2;//compares the values of the intermediate index and the value to find while (Arr[mid]! = value) {if (arr[mid]>val UE) {max = mid-1;} else if (arr[mid]<value) {min = mid + 1;} Add to Judge if (Min > Max) {return-1;} Mid = (max +min)/2;} return mid;}}

Operation Result:


4.7.3 Arrays

This class contains various methods for manipulating arrays, such as sorting and searching.

/* * Arrays: A tool class for manipulating arrays. such as sorting and finding. * 1:public static string toString (int[] a) turns the array into a string * 2:public static void sort (int[] a) sorts the arrays * 3:public static int bin Arysearch (int[] a,int key) binary lookup */public class Arraysdemo {public static void main (string[] args) {//define an array int[] arr = { };//public static string toString (int[] a) turns the array into a string System.out.println ("before sorting:" + arrays.tostring (arr)); /public static void sort (int[] a) sorts the array arrays.sort (ARR); System.out.println ("After sorting:" + arrays.tostring (arr));//public static int BinarySearch (int[] a,int key) binary lookup//[13, 24, 57, 6 9, 80]system.out.println ("BinarySearch:" +arrays.binarysearch (arr, 80));}}

Operation Result:


4.8 Regular Expressions

A regular expression uses a single string to describe and match a series of strings that conform to a certain syntactic rule.

4.8.1 rules for regular expressions


4.8.2 Regular expression judgment function

public boolean matches (string regex) method in the String class

Import java.util.scanner;/* * Check QQ number: * Requires 1:5-15 digits * requires 2:0 can not start * Analysis: * 1, keyboard input QQ number * 2, write a function to achieve check * 3, call function, output results */public CLA SS RegexDemo2 {public static void main (string[] args) {//Create keyboard object Scanner sc = new Scanner (system.in); System.out.println ("Please enter your QQ:"); String QQ = Sc.nextline (); System.out.println (CHECKQQ (QQ));} public static Boolean CHECKQQ (String qq) {//String regex = "[1-9][0-9]{4,14}";////public Boolean matches (string regex) informs this Whether the string matches the given regular expression//Boolean flag = Qq.matches (regex);//Return flag;//return Qq.matches ("[1-9][0-9]{4,14}"); return Qq.matches ("[1-9]\\d{4,14}");}}
Operation Result:



Exercise 1: Determine if a mobile phone number conforms to the rules

/* * Judgment Function *string class public boolean matches (String regex) * * Requirements: * Determine if the mobile phone number meets the requirements?  *  * Analysis: * A: Keyboard input mobile phone number * B: Define the mobile phone number rules * 13436975980 * 13688886868 * 13866668888 * 13456789012 * 13123456789 * 18912345678 * 18886867878 * 18638833883 * C: Call function, Judge can * D: output result *  rule: 11 digits * Start with 1 * Second digit is 3 or 8 */public class Regexdemo {public St atic void Main (string[] args) {//keypad input data Scanner sc = new Scanner (system.in); System.out.println ("Please enter the phone number to be judged:"); String phonenumber = Sc.nextline ();//define Cell phone number rule string regex = "1[38]\\d{9}";//Call Rule to determine Boolean flag = Phonenumber.matches (regex); System.out.println ("flag:" +flag);}}

Operation Result:


Exercise 2: Verifying a mailbox

/* * Check mailbox *  Analysis: * A: Keyboard Entry Email * B: Define the rules of the mailbox * [email protected] * [email protected] * [email protected] * [email protecte d] * [email protected] * C: Call function, Judge can * D: Output */public class Regextest {public static void main (string[] args) {//Keyboard entry Mailbox SC Anner sc = new Scanner (system.in); System.out.println ("Please enter e-mail:"); String email = sc.nextline ();//define the mailbox rule//string regex = "[A-za-z_0-9][email protected][a-za-z_0-9]{2,6} (\\.[ a-za-z_0-9]{2,3}) + "; String regex = "\\[email protected]\\w{2,6} (\\.\\w{2,3}) +";//Invoke function Boolean flag = email.matches (regex); System.out.println ("flag:" +flag);}}

Operation Result:


4.8.3 the segmentation function of regular Expressions

Public string[] Split (String regex) method in the String class

Import java.util.scanner;/* * Split function *string class public string[] Split (string regex) * Splits this string based on the match of the given regular expression. *  Example: * Lily net, Century Jia Yuan, cherish the net, QQ * Search Friends * Gender: Female * Range: "18-24" *  * age>=18 && age<=24 */public class Regexdem o {public static void main (string[] args) {//define an age search range string ages = "18-24";//define a rule String regex = "-";//Call method string[] Strar Ray = Ages.split (regex);//traverse//for (int x=0;x <strarray.length;x++) {//system.out.println (strarray[x]);//}// How do I get the int type? int startage = Integer.parseint (strarray[0]), int endage = Integer.parseint (strarray[1]);//keyboard input data Scanner sc = new Scanner (system.in); System.out.println ("Please enter your Age:"); int = Sc.nextint (); if (ages >=startage&&age<=endage) { System.out.println ("You are what I Want");} Else{system.out.println ("You're not what I'm looking for");}}
Operation Result:



Exercise 3:

public class RegexDemo2 {public static void main (string[] args) {//defines a string S1 = "AA,BB,CC"; string[] Str1array = S1.split (","); for (int x = 0; x <str1array.length;x++) {System.out.println (str1array[x]);} System.out.println ("---------------"); String s2 = "aa.bb.cc"; string[] Str2array = s2.split ("\ \"); for (int x = 0; x <str1array.length;x++) {System.out.println (str1array[x]);} System.out.println ("---------------"); String s3 = "AA  bb          cc"; string[] Str3array = s3.split ("+"); for (int x = 0; x <str1array.length;x++) {System.out.println (str1array[x]);} System.out.println ("---------------");//The path on the hard disk, we should use \ \ instead of string s4 = "F:\\java second quarter \\day14\\code\\day14_Regex\\src\\ Cn\\itcast_03 "; string[] Str4array = S4.split ("\\\\"); for (int x = 0; x <str1array.length;x++) {System.out.println (str1array[x]);} System.out.println ("---------------");}}

Operation Result:


Exercise 4:

/* * I'm like the next string: "91 27 46 38 50" * Please write code to achieve the final output is: "27 38 46 50 91" * * Analysis: * A: Define a String * B: Divide the string to get an array of strings * C: Transform the string array into int array * D: Sort int array * E: the sorted int array is assembled into a string * F: Output string */public class Regextest {public static void main (string[] args) {// Define a character string string s = "91 27 46 38 50";//Divide the string into string[] Strarray = S.split ("");//Convert the string array to an int array int[] arr = new Int[strarr ay.length];for (int x = 0; x < arr.length; × x + +) {Arr[x] = Integer.parseint (Strarray[x]);} Sorts an int array bubblesort (arr);//seceltsort (arr);//the sorted int array is assembled into a string/*string result = ""; for (int x = 0; x < arr.length; X + +) {String str = string.valueof (arr[x]); result + = Str;result + = "";} */stringbuilder sb = new StringBuilder (); for (int x = 0;x <arr.length;x++) {sb.append (arr[x]). Append (""); String result = sb.tostring (). Trim (); SYSTEM.OUT.PRINTLN (result);} Bubble sort public static void Bubblesort (int[] arr) {for (int x = 0; x < arr.length-1; + +) {for (int y = 0; y < arr.l Ength-1-X; y++) {if (Arr[y] > arr[y + 1]) {iNT TEMP = Arr[y];arr[y] = arr[y + 1];arr[y + 1] = temp;}}}} 

Operation Result:


4.8.4 the replacement function of regular expressions

public string ReplaceAll of the String class (String regex,string replacement)

/* * Replace function * Public  string ReplaceAll of String class (String regex,string replacement) *  using the given replacement Replace this string with all substrings that match the given regular expression.  */public class Regexdemo {public static void main (string[] args) {//define a string s = "hello1234worldkh6212260502006 823456 ";//I want to remove all the numbers, replace the string regex with" * "=" \\d "; String SS = "*"; String result = S.replaceall (regex, SS); SYSTEM.OUT.PRINTLN (result);}}

Operation Result:


4.8.5 the acquisition function of regular expressions

Use of the pattern class and the Matcher class

/* Get function: * Get the three-character word in the following String * da Jia ting wo shuo,jin tian Yao xia yu,bu Shang wan zi Xi,gao xing bu? */public class RegexDemo2 {public static void main (string[] args) {//define string s = "da Jia ting wo shuo,jin Tian Yao Xi A yu,bu shang wan zi Xi,gao xing bu?; /rule string regex = "\\b\\w{3}\\b";//compile the rule into pattern object pattern P = pattern.compile (regex);//Get Match object by pattern object Matcher m = P.matcher (s) ///Call the function of the match//find the sub-sequence that has not met//public Boolean find ()/* Boolean flag = M.find () by the Find method; SYSTEM.OUT.PRINTLN (flag); How do I get a value? Public * string Group () string ss = M.group (); SYSTEM.OUT.PRINTLN (ss); *  flag = M.find (); ss = M.group (); SYSTEM.OUT.PRINTLN (ss); */while (M.find ()) {System.out.println (M.group ());} Note: Be sure to first find () before group ()//Illegalstateexception:no match found//String ss = M.group ();//SYSTEM.OUT.PRINTLN (ss);}}

Operation Result:




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Dark Horse Programmer (Java) common class for----API (advanced operation of arrays, regular expressions)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.