gpt4 book ai didi

java - 如何去掉输出末尾的空格?

转载 作者:行者123 更新时间:2023-11-30 02:11:09 26 4
gpt4 key购买 nike

我的代码检查一定数量的用户输入的字符串是否有重复的字符。例如,如果我输入字符串“google”“paper”和“water”,则代码返回“paper”和“water”;因为“google”有两个操作系统。

我已经保存了代码部分,但是在打印时,输出的最后一个字符串后面出现了一个空格,我不知道如何删除它。

import java.util.Scanner;
import java.util.*;

class words{

public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");
boolean truth = false;

for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
for(int i=0;i<words.length;i++){
int j;
for(j=1;j<words[i].length();j++) {
if(words[i].charAt(j) == words[i].charAt(j-1)){
break;
}
}
if(j==words[i].length()){
truth = true;
System.out.print(words[i]+" ");
}
}
if(!truth){
System.out.println("NONE");
}
}
}

最佳答案

函数使逻辑可读

将检查重复字符的逻辑移至函数中;我会利用 String.toCharArray() 和更短的数组语法。就像,

private static boolean repeatedChars(String s) {
if (s == null) {
return false;
}
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length - 1; i++) {
if (chars[i] == chars[i + 1]) {
return true;
}
}
return false;
}

然后,您可以使用 lambda 来过滤 words基于它们没有重复的字符并收集 Collectors.joining(CharSequence) 喜欢

Scanner sc = new Scanner(System.in);
System.out.print("Enter the number or words: ");
String[] words = new String[sc.nextInt()];
System.out.print("Enter the strings: ");

for (int i = 0; i < words.length; i++) {
words[i] = sc.next();
}
System.out.println(Arrays.stream(words).filter(s -> !repeatedChars(s))
.collect(Collectors.joining(" ")));

并且,如果您需要显示 NONE您可以重复使用 Predicate<String> 的消息喜欢

Predicate<String> pred = s -> !repeatedChars(s);
if (Arrays.stream(words).anyMatch(pred)) {
System.out.println(Arrays.stream(words).filter(pred).collect(Collectors.joining(" ")));
} else {
System.out.println("NONE");
}

关于java - 如何去掉输出末尾的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50082018/

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