gpt4 book ai didi

java - 使用循环从字符串中删除空格

转载 作者:行者123 更新时间:2023-12-01 07:35:50 25 4
gpt4 key购买 nike

大家好,我正在尝试专门使用循环来删除空格。这是我到目前为止所想到的

    import java.util.Scanner;
public class Q2 {

public static void main(String[] args) {

String input = "";
char noSpace = ' ';

Scanner scan = new Scanner(System.in);
input = scan.nextLine();
System.out.println(input);

for (int i = 0; i < input.length(); i++) { //search from right to left
for (int j = input.length(); j != -1; j--) { //search from left to right
if (input.charAt(i) == noSpace) { //if there is a space move position of i and j
i++;
j--;
}




}
System.out.println(input);

我对java还是很陌生,任何建议都会非常感谢!

最佳答案

试试这个:

public class RemoveWhiteSpace {

public static void main(String[] args) {

String str = "Hello World... Hai... How are you? .";
for(Character c : str.toCharArray()) {
if(!Character.isWhitespace(c)) // Check if not white space print the char
System.out.print(c);
}
}
}

关于java - 使用循环从字符串中删除空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12256866/

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