2016-04-26 75 views
0

我確信這很簡單,但是我試着用google搜索這個問題,但找不到適合我的問題的答案。Java:檢查字符串中的每個空格

我在玩弄字符串處理,我試圖做的事情之一就是獲取每個單詞的第一個字母。 (然後將它們全部放入一個字符串中)

我在註冊每個'空格'時遇到問題,因此我的If語句將被觸發。這是迄今爲止我所擁有的。

while (scanText.hasNext()) { 
     boolean isSpace = false; 
     if (scanText.hasNext(" ")) {isSpace = true;} 

     String s = scanText.next(); 

     if (isSpace) {firstLetters += s + " ";} 
    } 

而且,如果有更好的方法來做到這一點,那麼請讓我知道

+0

「掃描儀」可能會佔用白色空間,因爲它使用空格作爲單詞分隔符。你應該檢查一些其他的字符串來獲得輸入的空白​​區域,或者根本不需要從輸入中獲取空間,只需將它添加到單詞中即可。 – 11thdimension

回答

0

您還可以將原始文本拆分爲空格並收集單詞。

String input = " Hello world aaa  "; 
String[] split = input.trim().split("\\s+"); // all types of whitespace; " +" to pick spaces only 
// operate on "split" array containing words now: [Hello, world, aaa] 

但是,在這裏使用正則表達式可能會矯枉過正。

+1

我自己設法解決了一個問題。這樣做會有什麼不利嗎?對不起,我無法在評論中格式化。 private static String firstLetters(String original){ \t \t Scanner scanText = new Scanner(original); \t \t String firstLetters =「」; \t \t而(scanText.hasNext()){ \t \t \t串字= scanText.next(); \t \t \t firstLetters + = word.substring(0,1).toUpperCase()+「」; \t \t} \t \t \t \t scanText.close(); \t \t return firstLetters; } – Scott

+1

沒關係。就我個人而言,我會用firstLetters + = Character.toUpperCase(word.charAt(0))+「」替換firstLetter加法;擺脫子串(因爲我認爲_charAt_喚起了更好的意圖)。 稍後,您可能需要閱讀有關https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html的文章,該文章提供了更便宜的字符串連接(您不需要在中間構造弦一直)。 –