1. 程式人生 > >算法筆記_221:串的簡單處理(Java)

算法筆記_221:串的簡單處理(Java)

bsp 串的簡單處理 它的 public 劃線 ati href block 規則

目錄

1 問題描述

2 解決方案


1 問題描述

串的處理
在實際的開發工作中,對字符串的處理是最常見的編程任務。本題目即是要求程序對用戶輸入的串進行處理。具體規則如下:
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個字符。


2 解決方案

 1 import java.util.ArrayList;
 2 import java.util.Scanner;
 3 
 4 public class Main {
 5     public static ArrayList<Character> list = new ArrayList<Character>();
 6     
 7     public void getResult(String A) {
 8         char[] arrayA = A.toCharArray();
9 for(int i = 0;i < arrayA.length;i++) { 10 if(arrayA[i] == ‘ ‘) 11 continue; 12 char temp = arrayA[i]; 13 if(temp >= ‘0‘ && temp <= ‘9‘) { 14 list.add(temp); 15 } else { 16 temp = (char
) (temp - 32); 17 list.add(temp); 18 } 19 if(i == arrayA.length - 1) 20 break; 21 temp = arrayA[++i]; 22 while(temp != ‘ ‘) { 23 char t = arrayA[i - 1]; 24 if(t >= ‘0‘ && t <= ‘9‘ && temp >= ‘a‘ && temp <= ‘z‘) 25 list.add(‘_‘); 26 else if(t >= ‘a‘ && t <= ‘z‘ && temp >= ‘0‘ && temp <= ‘9‘) 27 list.add(‘_‘); 28 list.add(temp); 29 if(i == arrayA.length - 1) 30 break; 31 temp = arrayA[++i]; 32 } 33 list.add(‘ ‘); 34 } 35 for(int i = 0;i < list.size();i++) 36 System.out.print(list.get(i)); 37 } 38 39 public static void main(String[] args) { 40 Main test = new Main(); 41 Scanner in = new Scanner(System.in); 42 String A = in.nextLine(); 43 test.getResult(A); 44 } 45 }

運行結果:

50cat do60     s1t2k30
50_cat Do_60 S_1_t_2_k_30 

算法筆記_221:串的簡單處理(Java)