一:根据某种规则缩短字符串
/* * 根据规则缩短字符串 */ 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); } }
时间: 2024-10-11 22:43:40