標籤: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—————對字串相關演算法