Java实现的文本字符串操作工具类实例【数据替换,加密解密操作】
本文实例讲述了Java实现的文本字符串操作工具类。分享给大家供大家参考,具体如下:
packagecom.gcloud.common; importorg.apache.commons.lang.StringUtils; importjava.security.MessageDigest; importjava.security.NoSuchAlgorithmException; importjava.text.BreakIterator; importjava.util.ArrayList; importjava.util.Date; importjava.util.Random; /** *文本字符串工具类 *Createdbycharlinon2017/9/10. */ publicclassTextUtil{ privatestaticfinalchar[]QUOTE_ENCODE=""".toCharArray(); privatestaticfinalchar[]AMP_ENCODE="&".toCharArray(); privatestaticfinalchar[]LT_ENCODE="<".toCharArray(); privatestaticfinalchar[]GT_ENCODE=">".toCharArray(); privatefinalstaticString[]hex={"00","01","02","03","04","05", "06","07","08","09","0A","0B","0C","0D","0E","0F","10", "11","12","13","14","15","16","17","18","19","1A","1B", "1C","1D","1E","1F","20","21","22","23","24","25","26", "27","28","29","2A","2B","2C","2D","2E","2F","30","31", "32","33","34","35","36","37","38","39","3A","3B","3C", "3D","3E","3F","40","41","42","43","44","45","46","47", "48","49","4A","4B","4C","4D","4E","4F","50","51","52", "53","54","55","56","57","58","59","5A","5B","5C","5D", "5E","5F","60","61","62","63","64","65","66","67","68", "69","6A","6B","6C","6D","6E","6F","70","71","72","73", "74","75","76","77","78","79","7A","7B","7C","7D","7E", "7F","80","81","82","83","84","85","86","87","88","89", "8A","8B","8C","8D","8E","8F","90","91","92","93","94", "95","96","97","98","99","9A","9B","9C","9D","9E","9F", "A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA", "AB","AC","AD","AE","AF","B0","B1","B2","B3","B4","B5", "B6","B7","B8","B9","BA","BB","BC","BD","BE","BF","C0", "C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB", "CC","CD","CE","CF","D0","D1","D2","D3","D4","D5","D6", "D7","D8","D9","DA","DB","DC","DD","DE","DF","E0","E1", "E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC", "ED","EE","EF","F0","F1","F2","F3","F4","F5","F6","F7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F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F, 0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F,0x3F}; privatestaticMessageDigestdigest=null; /** *替换字符串 *@paramline *@paramoldStr *@paramnewStr *@return */ publicstaticStringreplace(Stringline,StringoldStr,StringnewStr){ if(StringUtils.isEmpty(line))returnnull; intindex=0; if((index=line.indexOf(oldStr,index))>=0){ char[]charArray=line.toCharArray(); char[]newStrArray=newStr.toCharArray(); intoldLen=oldStr.length(); StringBufferbuf=newStringBuffer(charArray.length); buf.append(charArray,0,index).append(newStrArray); index+=oldLen; inti=index; while((index=line.indexOf(oldStr,index))>0){ buf.append(charArray,i,index-i).append(newStrArray); index+=oldLen; i=index; } buf.append(charArray,i,charArray.length-i); returnbuf.toString(); } returnline; } /** *替换字符串,并存入替换次数 *@paramline *@paramoldStr *@paramnewStr *@return */ publicstaticStringreplace(Stringline,StringoldStr,StringnewStr,int[]countArr){ if(StringUtils.isEmpty(line))returnnull; intindex=0; if((index=line.indexOf(oldStr,index))>=0){ intcount=0; count++; char[]charArray=line.toCharArray(); char[]newStrArray=newStr.toCharArray(); intoldLen=oldStr.length(); StringBufferbuf=newStringBuffer(charArray.length); buf.append(charArray,0,index).append(newStrArray); index+=oldLen; inti=index; while((index=line.indexOf(oldStr,index))>0){ buf.append(charArray,i,index-i).append(newStrArray); index+=oldLen; i=index; count++; } buf.append(charArray,i,charArray.length-i); countArr[0]=count; returnbuf.toString(); } returnline; } /** *替换字符串,不区分大小写 *@paramline *@paramoldStr *@paramnewStr *@return */ publicstaticStringreplaceIgnoreCase(Stringline,StringoldStr,StringnewStr){ if(StringUtils.isEmpty(line))returnnull; intindex=0; line=line.toLowerCase(); oldStr=oldStr.toLowerCase(); if((index=line.indexOf(oldStr,index))>=0){ char[]charArray=line.toCharArray(); char[]newStrArray=newStr.toCharArray(); intoldLen=oldStr.length(); StringBufferbuf=newStringBuffer(charArray.length); buf.append(charArray,0,index).append(newStrArray); index+=oldLen; inti=index; while((index=line.indexOf(oldStr,index))>0){ buf.append(charArray,i,index-i).append(newStrArray); index+=oldLen; i=index; } buf.append(charArray,i,charArray.length-i); returnbuf.toString(); } returnline; } /** *替换字符串,不区分大小写,并存入替换次数 *@paramline *@paramoldStr *@paramnewStr *@return */ publicstaticStringreplaceIgnoreCase(Stringline,StringoldStr,StringnewStr,int[]countArr){ if(StringUtils.isEmpty(line))returnnull; intindex=0; line=line.toLowerCase(); oldStr=oldStr.toLowerCase(); if((index=line.indexOf(oldStr,index))>=0){ char[]charArray=line.toCharArray(); char[]newStrArray=newStr.toCharArray(); intoldLen=oldStr.length(); StringBufferbuf=newStringBuffer(charArray.length); buf.append(charArray,0,index).append(newStrArray); index+=oldLen; inti=index; intcount=0; while((index=line.indexOf(oldStr,index))>0){ count++; buf.append(charArray,i,index-i).append(newStrArray); index+=oldLen; i=index; } buf.append(charArray,i,charArray.length-i); countArr[0]=count; returnbuf.toString(); } returnline; } /** *替换页面html标签 *@paramhtmlStr *@return */ publicstaticStringescapeHTMLTags(StringhtmlStr){ if(StringUtils.isEmpty(htmlStr))returnnull; charch; intlast=0; char[]htmlStrArr=htmlStr.toCharArray(); intlen=htmlStrArr.length; StringBufferoutBuf=newStringBuffer((int)(len*1.3)); inti=0; for(;i'>'){ continue; }elseif(ch=='<'){ if(i>last){ outBuf.append(htmlStrArr,last,i-last); } last=i+1; outBuf.append(LT_ENCODE); }elseif(ch=='>'){ if(i>last){ outBuf.append(htmlStrArr,last,i-last); } last=i+1; outBuf.append(GT_ENCODE); } } if(last==0){ returnhtmlStr; } if(i>last){ outBuf.append(htmlStrArr,last,i-last); } returnoutBuf.toString(); } /** *HashesaStringusingtheMd5algorithmandreturnstheresultasa *Stringofhexadecimalnumbers.Thismethodissynchronizedtoavoid *excessiveMessageDigestobjectcreation.Ifcallingthismethodbecomesa *bottleneckinyourcode,youmaywishtomaintainapoolofMessageDigest *objectsinsteadofusingthismethod. *@paramdata *@return */ publicsynchronizedstaticStringhash(Stringdata){ if(digest==null){ try{ digest=MessageDigest.getInstance("MD5"); }catch(NoSuchAlgorithmExceptione){ System.err.println("FailedtoloadtheMD5MessageDigest.Jivewillbeunabletofunctionnormally."); e.printStackTrace(); } } digest.update(data.getBytes()); returnencodeHex(digest.digest()); } /** *TurnsanarrayofbytesintoaStringrepresentingeachbyteasan *unsignedhexnumber. *@parambytes *@return */ publicstaticfinalStringencodeHex(byte[]bytes){ StringBufferbuf=newStringBuffer(bytes.length*2); inti; for(i=0;i >2)&0x3f; ret.append(cvt.charAt(c)); c=(data[i]<<4)&0x3f; if(++i >4)&0x0f; ret.append(cvt.charAt(c)); if(i >6)&0x03; ret.append(cvt.charAt(c)); }else{ ++i; ret.append((char)fillchar); } if(i >4)&0x3)); ret.append((char)c); if(++i >2)&0xf); ret.append((char)c1); } if(++i 0){ wordList.add(tmp); } } return(String[])wordList.toArray(newString[wordList.size()]); } /** *Pseudo-randomnumbergeneratorobjectforusewithrandomString().The *Randomclassisnotconsideredtobecryptographicallysecure,soonly *usetheserandomStringsforlowtomediumsecurityapplications. */ privatestaticRandomrandGen=newRandom(); /** *Arrayofnumbersandlettersofmixedcase.Numbersappearinthelist *twicesothatthereisamoreequalchancethatanumberwillbepicked. *Wecanusethearraytogetarandomnumberorletterbypickingarandom *arrayindex. */ privatestaticchar[]numbersAndLetters=("0123456789abcdefghijklmnopqrstuvwxyz"+"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray(); /** *ReturnsarandomStringofnumbersandletters(loweranduppercase)of *thespecifiedlength.ThemethodusestheRandomclassthatisbuilt-in *toJavawhichissuitableforlowtomediumgradesecurityuses.This *meansthattheoutputisonlypseudorandom,i.e.,eachnumberis *mathematicallygeneratedsoisnottrulyrandom. *@paramlengththedesiredlengthoftherandomStringtoreturn. *@returnarandomStringofnumbersandlettersofthespecifiedlength. */ publicstaticfinalStringrandomString(intlength){ if(length<1){ returnnull; } char[]randBuffer=newchar[length]; for(inti=0;i length,theStringwillbe *choppedthere.Ifnonewlineorwhitespaceisfoundin * string
uptotheindexlength
,theString *willchoppedatlength
. **Forexample,chopAtWord("ThisisaniceString",10)willreturn"Thisis *a"whichisthefirstwordboundarylessthanorequalto10characters *intotheoriginalString. *@paramstringtheStringtochop. *@paramlength *@returnasubstringof
string
whoselengthislessthanor *equaltolength
,andthatischoppedat *whitespace. */ publicstaticfinalStringchopAtWord(Stringstring,intlength){ if(string==null){ returnstring; } char[]charArray=string.toCharArray(); intsLength=string.length(); if(length0;i--){ if(charArray[i]==''){ returnstring.substring(0,i).trim(); } } //DidnotfindwordboundarysoreturnoriginalStringchoppedat //specifiedlength. returnstring.substring(0,length); } /** *EscapesallnecessarycharactersintheStringsothatitcanbeusedin *anXMLdoc. *@paramstringthestringtoescape. *@returnthestringwithappropriatecharactersescaped. */ publicstaticfinalStringescapeForXML(Stringstring){ if(string==null){ returnnull; } charch; inti=0; intlast=0; char[]input=string.toCharArray(); intlen=input.length; StringBufferout=newStringBuffer((int)(len*1.3)); for(;i '>'){ continue; }elseif(ch=='<'){ if(i>last){ out.append(input,last,i-last); } last=i+1; out.append(LT_ENCODE); }elseif(ch=='&'){ if(i>last){ out.append(input,last,i-last); } last=i+1; out.append(AMP_ENCODE); }elseif(ch=='"'){ if(i>last){ out.append(input,last,i-last); } last=i+1; out.append(QUOTE_ENCODE); } } if(last==0){ returnstring; } if(i>last){ out.append(input,last,i-last); } returnout.toString(); } /** *UnescapestheStringbyconvertingXMLescapesequencesbackintonormal *characters. *@paramstringthestringtounescape. *@returnthestringwithappropriatecharactersunescaped. */ publicstaticfinalStringunescapeFromXML(Stringstring){ string=replace(string,"<","<"); string=replace(string,">",">"); string=replace(string,""","\""); returnreplace(string,"&","&"); } publicstaticStringescape(Strings){ StringBuffersbuf=newStringBuffer(); intlen=s.length(); for(inti=0;i >>8)]); sbuf.append(hex[(0x00FF&ch)]); } } returnsbuf.toString(); } publicstaticStringunescape(Strings){ StringBuffersbuf=newStringBuffer(); inti=0; intlen=s.length(); while(i lengthof16. * *@paramstring *theoriginalStringtopad. *@paramlength *thedesiredlengthofthenewpaddedString. *@returnanewStringpaddedwiththerequirednumberof0's. */ publicstaticfinalStringzeroPadString(Stringstring,intlength){ if(string==null||string.length()>length){ returnstring; } StringBufferbuf=newStringBuffer(length); buf.append(zeroArray,0,length-string.length()).append(string); returnbuf.toString(); } /** *FormatsaDateasafifteencharacterlongStringmadeupoftheDate's *paddedmillisecondvalue. *@returnaDateencodedasaString. */ publicstaticfinalStringdateToMillis(Datedate){ returnzeroPadString(Long.toString(date.getTime()),15); } publicstaticvoidmain(String[]args){ System.out.println(replace("aaaaabbbcccc","aa","gg")); System.out.println(replaceIgnoreCase("AAAAbbbcccc","aa","gg")); System.out.println(escapeHTMLTags("AAAAbb ")); } }
更多关于java算法相关内容感兴趣的读者可查看本站专题:《Java字符与字符串操作技巧总结》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》
希望本文所述对大家java程序设计有所帮助。