如何使输出包含所需的空间?

时间:2019-05-15 17:20:11

标签: java loops char spacing

我必须将传递给字符串的每个单词的首字母大写。我的输出在进行大写,但是并没有保持原始输出的格式。例如,字符串输入是“ hello world”,我的输出是“ HelloWorld”,而我想要的输出应该是“ Hello World”。

我试图在整个代码中添加空格,但没有任何效果。我认为问题是当我使用toCharArray时,它给我的输出没有空格?因此,我的串联结果是将所有内容一次添加,而不是每个单词单独添加?

或者我以为我的代码对结果使用了字符串连接,并且没有将其分开,因为我有两个单词都输入同一个变量。

import java.util.*; 
import java.io.*;

    class Main {  
      public static String LetterCapitalize(String str) { 

        // code goes here   
        String[] word = str.split(" ");
        String result = "";


        for(int i = 0; i < word.length; i++) {

            char[] charWord = word[i].toCharArray();

            for(int j = 0; j < charWord.length; j++ ) {
            String cap = word[i].charAt(0) + "";
            cap = cap.toUpperCase();
            //System.out.print(" ");
            result += (j == 0 ? cap : word[i].charAt(j));
        }

        }

        return result;


      } 

      public static void main (String[] args) {  
        // keep this function call here     
        Scanner s = new Scanner(System.in);
        System.out.print(LetterCapitalize(s.nextLine())); 
      }   

   }

没有错误。只是没有得到想要的输出。

3 个答案:

答案 0 :(得分:1)

当您完成String[] word = str.split(" ");时,每个单词之间的空格都被取出,现在只剩下数组中的单词。您应该在生成的单词数组上使用String.join(" ", word)来反转效果,以便获得空格。

请尝试按以下步骤操作:

for(int i = 0; i < word.length; i++) {
    word[i] = word[i].substring(0, 1).toUpperCase() + word[i].substring(1);
}
result = String.join(" ", word);

答案 1 :(得分:0)

尝试一下:

import java.util.*;

class Main {  
  public static String LetterCapitalize(String str) { 

    // code goes here   
    String[] word = str.split(" ");
    String result = "";

    for(int i = 0; i < word.length; i++) {
        result += capitalize(word[i]) + (i != word.length - 1 ? " " : "");
    }

    return result;
  }

  private static String capitalize(String s){
      return Character.toUpperCase(s.charAt(0)) + s.substring(1);
  }

  public static void main (String[] args) {  
    // keep this function call here     
    Scanner s = new Scanner(System.in);
    System.out.print(LetterCapitalize(s.nextLine())); 
  }   
}

答案 2 :(得分:0)

您可以使用以下代码。

class Main {
public static String LetterCapitalize(String str) {

    // code goes here
    String[] word = str.split(" ");
    StringBuilder result = new StringBuilder();


    for (int i = 0; i < word.length; i++) {

        char[] charWord = word[i].toCharArray();

        for (int j = 0; j < charWord.length; j++) {
            String cap = word[i].charAt(0) + "";
            cap = cap.toUpperCase();
            //System.out.print(" ");
            result.append(j == 0 ? cap : word[i].charAt(j));
        }
        result.append(" ");
    }

    return result.toString();


}

public static void main(String[] args) {
    // keep this function call here
    Scanner s = new Scanner(System.in);
    System.out.print(LetterCapitalize(s.nextLine()));
}

}

相关问题