Java演算法解析3—————對字串相關演算法

來源:互聯網
上載者:User

標籤:java   java演算法   

一:根據某種規則縮短字串

/* * 根據規則縮短字串 */public class Dome07 {public static void main(String[] args) {String str = "C:\\Windows\\Resources\\Themes\\aero";while (true) {System.out.println(str);int endIndex = str.lastIndexOf("\\");// 截取字串str = str.substring(0, endIndex);//substring(start,end)方法的範圍:[start,end)if (str.indexOf("\\") == -1) {System.out.println(str);return; // 退出程式}}}}


 

二:統計字串中不同類型字元的個數

/* * 統計字串不同字元類型的個數 */public class Dome08 {public static void main(String[] args) {String str = "天氣,tianqi/,//t232aA{{";System.out.printf("字串長度:%d\n", str.length());// 英語,中文,數字,其他StringBuilder[] sb = new StringBuilder[4];for (int i = 0; i < sb.length; i++) {// StringBuilder初始化sb[i] = new StringBuilder();}for (int i = 0; i < str.length(); i++) {// 包含所有英文字母if (str.charAt(i) >= 'A' && str.charAt(i) <= 'z') {sb[0].append(str.charAt(i));// 判斷所有中文} else if (str.charAt(i) >= 19968 && str.charAt(i) <= 171941) {sb[1].append(str.charAt(i));// 數字} else if (str.charAt(i) >= '1' && str.charAt(i) <= '9') {sb[2].append(str.charAt(i));} else {sb[3].append(str.charAt(i));}}for (int i = 0; i < sb.length; i++) {System.out.printf("%d\t%s\n", sb[i].length(), sb[i].toString());}}}


 

三:實現一個函數,把字串中的每個空格替換成“%20”

例如輸入“I am Tom”,則輸出“I%20am%20Tom”

public class Dome06 {public void replaceBlank(char string[], int length) {if (string == null || length <= 0)return;int originalLength = 0;int numberOfBlank = 0;int i = 0;System.out.println(string);while (string[i] != '\0') {++originalLength;if (string[i] == ' ')++numberOfBlank;++i;}int newLength = originalLength + numberOfBlank * 2;if (newLength > length)return;int indexOfOriginal = originalLength;int indexOfNew = newLength;while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal) {if (string[indexOfOriginal] == ' ') {string[indexOfNew--] = '0';string[indexOfNew--] = '2';string[indexOfNew--] = '%';} else {string[indexOfNew--] = string[indexOfOriginal];}--indexOfOriginal;}System.out.println(string);}public static void main(String[] args) {char[] originalStr = new char[30];originalStr[0] = 'I';originalStr[1] = ' ';originalStr[2] = 'a';originalStr[3] = 'm';originalStr[4] = ' ';originalStr[5] = 'T';originalStr[6] = 'o';originalStr[7] = 'm';originalStr[8] = '.';new Dome06().replaceBlank(originalStr, 30);}}


 

Java演算法解析3—————對字串相關演算法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.