Java演算法--串的簡單處理,java演算法--
題目如下:
串的處理
在實際的開發工作中,對字串的處理是最常見的編程任務。
本題目即是要求程式對使用者輸入的串進行處理。具體規則如下:
1. 把每個單詞的首字母變為大寫。
2. 把數字與字母之間用底線(_)分開,使得更清晰
3. 把單詞中間有多個空格的調整為1個空格。
例如:
使用者輸入:
you and me what cpp2005program
則程式輸出:
You And Me What Cpp_2005_program
使用者輸入:
this is a 99cat
則程式輸出:
This Is A 99_cat
我們假設:使用者輸入的串中只有小寫字母,空格和數字,不含其它的字母或符號。
每個單詞間由1個或多個空格分隔。
假設使用者輸入的串長度不超過200個字元。
方法一:
public class 串的簡單處理 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String string = scanner.nextLine(); Vector<Character> vector = new Vector<Character>(); for (int i = 0; i < string.length(); i++) { vector.add(string.charAt(i)); } try { int index = 0; while (index < vector.size()) { //判斷第一個是否為小寫英文字元,是的話進行操作 if (index == 0 && vector.elementAt(index) >= 'a' && vector.elementAt(index) <= 'z') { //Replaces the element at the specified position in this Vector with the specified element vector.set(index,(char) (vector.elementAt(index) - ('a' - 'A'))); } else if (vector.elementAt(index - 1) == ' '&& vector.elementAt(index) == ' ') { //處理有多個空格的可能 vector.remove(index); index--; } else if (vector.elementAt(index - 1) == ' ' && (vector.elementAt(index) >= 'a' && vector .elementAt(index) <= 'z')) { //判斷是空格後邊的字元 vector.set(index, (char) (vector.elementAt(index) - ('a' - 'A'))); } else if ((vector.elementAt(index) >= 'a' && vector .elementAt(index) <= 'z') && (vector.elementAt(index - 1) >= '0' && vector .elementAt(index - 1) <= '9')) { vector.add(index, '_'); index++; } else if ((vector.elementAt(index - 1) >= 'a' && vector .elementAt(index - 1) <= 'z') && (vector.elementAt(index) >= '0' && vector .elementAt(index) <= '9')) { //判斷的是數字 vector.add(index, '_'); index++; } index++; } for (int i = 0; i < vector.size(); i++) { System.out.print(vector.elementAt(i)); } System.out.println(); } catch (ArrayIndexOutOfBoundsException e) { } }}
方法二:主要用到Regex對字串進行截取,然後對每一個字元數組的元素進行正則匹配,含有數位單獨進行處理
public class SimpleString { // 列印字串的函數 public static void print(String[] s) { for (int i = 0; i < s.length - 1; i++) { System.out.print(s[i] + " "); } System.out.println(s[s.length - 1]); } public static void main(String[] args) { Scanner scan = new Scanner(System.in); String s = scan.nextLine(); String[] ss = s.split("[\\s]+"); // 根據Regex,刪除一個或多個空格,將字串儲存為字元數組 for (int i = 0; i < ss.length; i++) { // 將每一個字元數組的首字母改為大寫 String up = ("" + ss[i].charAt(0)).toUpperCase(); // 大寫 StringBuffer sb = new StringBuffer(ss[i]); ss[i] = sb.replace(0, 1, up).toString(); // 上邊已經把字串數組的首字母該為大寫,然後對更改後的字元數組判斷是否有數字 Matcher m = Pattern.compile("\\d+").matcher(ss[i]);// 0-9出現一次或多次 while (m.find()) { // m.group():Returns the input subsequence matched by the previous match String num = new String(m.group()); String num2 = num; num2 = "_" + num + "_"; // 數字前後都添加"_" ss[i] = ss[i].replace(num, num2); if (ss[i].startsWith("_")) { // 去頭"_" ss[i] = ss[i].substring(1); } if (ss[i].endsWith("_")) { // 去尾"_" ss[i] = ss[i].substring(0, ss[i].length() - 1); } } } print(ss); }}