删除Array中的最后一个空格 - java

时间:2017-12-29 10:03:27

标签: java arrays

我的程序必须用大写字母向后打印单词,并在每行的末尾打印一个点。你可以帮我删除点之前的最后一个空格吗?

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int pocet = sc.nextInt();
    sc.nextLine();
    for (int i = 0; i < pocet; i++) {
        String veta = sc.nextLine();
        String veta2=veta.replaceAll("\\s+"," ");
        String[] words = veta2.split(" "); 
        String result = "";
        for (int j = 0; j<words.length;j++){
            for (int k = words[j].length(); k > 0; k--) {
            result = result + words[j].substring(k - 1, k);

            }
        words[j] = result;
        result = "";
        //return result.replaceAll("\\s+$", "");
        }

        words[words.length-1]= words[words.length-1];

        System.out.println();

    for (int j =0; j<words.length; j++){
        char whitespace = ' ';
         System.out.print(words[j].toUpperCase()+whitespace);
     }
    }
    System.out.print(".");
    System.out.println();

  }    
}

由于

3 个答案:

答案 0 :(得分:1)

用以下代码替换你的:

for (int j =0; j<words.length; j++){
     char whitespace = ' ';
     System.out.print(words[j].toUpperCase());
     if (j < (words.length - 1)) {
         System.out.print(whitespace);
    }
}

这样,除了数组的最后一个单词外,你将添加一个空格

答案 1 :(得分:0)

只需使用String.join来连接由String分隔的CharSequence(此处为空格)而不是for循环。

String wordString = String.join(" ", words);

在那里,你不需要删除任何东西。在打印之前,您仍需要对结果执行大写操作。

wordString = wordString.toUpperCase()
System.out.println(wordString);

答案 2 :(得分:0)

public static void main(String [] args){         Scanner in = new Scanner(System.in);

    System.out.printf("Please insert number of lines you want to enter: ");        
    String[] input = new String[in.nextInt()];
    in.nextLine(); 

    for (int i = 0; i < input.length; i++) {
        input[i] = in.nextLine();
    }
    String output = null;
   for(int i=0;i<input.length;i++) {
       output="";
       String[] lst = new String[input[i].split(" ").length];
       lst = input[i].split(" ");

        for(int j = lst.length-1; j >= 0; j--) {

            output+=(j==0)?lst[j]+".":lst[j]+" ";
        }
        System.out.println(output);
   }

}