2016-04-26 56 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的文章,该文章提供了更便宜的字符串连接(您不需要在中间构造弦一直)。 –