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

來源:互聯網
上載者:User

標籤:處理   style   數字   public   符號   底線   ring   res   題目   

目錄

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     s1t2k3050_cat Do_60 S_1_t_2_k_30 

 

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.