標籤:search tar print 驗證郵箱 字串 遞迴 參數 ack 實驗
Program:按照下面要求實現字串的操作:
(1)設計一個提供下面字串操作的類
1)編寫一個方法,尋找在一個字串中指定字串出現的次數。
2)編寫一個方法,參數(母字串,目標字串,替換字串)將母字串中的所有目標字元用替換字串替換。
3)編寫一個方法,判斷一個email地址是否合法。
(2)編寫一個測試類別,對(1)中的字串類的方法逐一進行測試。
Description:前兩個問題採用遞迴實現,最後一個問題,採用正則驗證。代碼如下:
1 /* 2 * Description:採用遞迴實現字串操作類 3 * 4 * */ 5 6 package tools; 7 8 9 public class Operate {10 11 //遞迴尋找字串中指定字元出現的次數12 public static int searchEleNum(String str,String targetEle) { //參數為字串和指定字元13 14 if( str.indexOf(targetEle) == -1 ) {15 return 0;16 }else {17 //從當前找到位置的下一個位置下標開始,截取字串,再進行遞迴18 return 1 + searchEleNum( str.substring( str.indexOf( targetEle ) + 1 ),targetEle);19 }20 }21 22 23 //遞迴替換,將母字串的目標字串,替換成指定字串24 public static String replaceAll(String parent,String targetEle,String replaceEle ) {25 26 //當目標元素不存在時,返回母字串27 if( parent.indexOf(targetEle) == -1 ) {28 29 return parent;30 }else { //目標元素存在時,採用截取的方式進行遞迴31 32 //擷取目標元素開始下標33 int beginIndex = parent.indexOf(targetEle);34 //擷取目標元素結束位置的下一位置下標35 int endIndex = beginIndex + targetEle.length();36 37 //採用遞迴的方法,截取目標元素在parent中的前面字串 + 替換字串 + 目標元素在parent中的後面字串遞迴38 //注意:substring()方法,當有兩個參數時,後者所表示下標元素取不到39 return parent.substring(0,beginIndex) + replaceEle +40 replaceAll(parent.substring(endIndex), targetEle, replaceEle);41 }42 43 }44 45 //判斷email地址是否合法46 public static boolean ifEmeil(String email) {47 48 //字串不為空白49 if( email != null && !"".equals(email) ) {50 51 //採用正則驗證郵箱地址合法性52 if( email.matches( "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$" ) ) { 53 54 return true;55 }else {56 57 return false;58 }59 }60 61 return false;62 }63 64 }
1 /* 2 * Description:字串操作 3 * 4 * Written By:Cai 5 * 6 * Date Written:2017-09-25 7 * 8 * */ 9 10 package main;11 12 import tools.Operate;13 14 15 public class DemoThree4 {16 17 public static void main(String args[]) {18 19 String str1 = "hello world"; //聲明並初始化一個字串變數20 21 String email = "[email protected]"; //設定QQ郵箱地址,驗證email合法性22 23 //測試尋找字串出現次數的方法24 System.out.println( str1 + "中,字元‘l’出現的次數為:" + Operate.searchEleNum(str1, "l") );25 //測試替換指定字元的方法26 System.out.println( str1 + "中,替換所有字元‘l’為字元6:" + Operate.replaceAll(str1, "l", "6") );27 28 //驗證email地址合法性29 System.out.println( Operate.ifEmeil(email) );30 System.out.println( Operate.ifEmeil(str1));31 32 }33 34 }
Java實驗項目三——遞迴實現字串尋找和替換操作