gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:21:41 24 4
gpt4 key购买 nike

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

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();

}
}

谢谢

最佳答案

将您的 for 替换为以下代码:

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);
}
}

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

关于java - 删除数组中的最后一个空格 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48020788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com