IMAUOJ-1241 Problem B:英文短語縮寫
阿新 • • 發佈:2018-12-19
題目描述
對給定的英文短語寫出它的縮寫,比如我們經常看到的SB就是Safe Browsing的縮寫。
輸入
輸入的第一行是一個整數T,表示一共有T組測試資料。
接下來有T行,每組測試資料佔一行,每行有一個英文短語,每個英文短語由一個或多個單片語成;每組的單詞個數不超過10個,每個單詞有一個或多個大寫或小寫字母組成;
單詞長度不超過10,由一個或多個空格分隔這些單詞。
輸出
請為每組測試資料輸出規定的縮寫,每組輸出佔一行。
樣例輸入
end of file
樣例輸出
EOF
個人題目思路
利用Stirng類的split方法將輸入的字串根據空格分割成字串陣列,遍歷字串陣列,當字串陣列元素不是單空格(即length>0,這種情況在輸入兩個空格時會出現)時,把元素的charAt(0)累加到空白字串中,最後將累加好的字串全部轉大寫輸出。
原始碼
import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); while(sc.hasNext()) { int t=sc.nextInt(); sc.nextLine(); while(t-->0){ String str=sc.nextLine(); String[] s=str.split(" "); String result=""; for(int i=0;i<s.length;i++){ if(s[i].length()>=1) result+=s[i].charAt(0); } System.out.println(result.toUpperCase()); } } } }
注:
String中的split(",")和split(",",-1)的區別
1、當字串最後一位有值時,兩者沒有區別
2、當字串最後一位或者N位是分隔符時,前者不會繼續切分,而後者繼續切分。即前者不保留null值,後者保留。
package stringsplit; public class stringSplit { public static void main(String[] args) { String line = "hello,,world,,,"; String res1[] = line.split(","); String res2[] = line.split(",", -1); int i=1; for(String r: res1) System.out.println(i+++r); System.out.println("========================"); i=1; for(String r: res2) System.out.println(i+++r); } }
輸出結果是:
1hello
2
3world
========================
1hello
2
3world
4
5
6