0

こんにちはみんな私は特にループを使用して空白を削除しようとしています。これが私がこれまでに思いついたものです

    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にまったく慣れていないので、どんな提案でも大いに感謝します!

4

6 に答える 6

4

これを試してください:

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);
        }
    }
}
于 2012-09-04T04:55:50.940 に答える
1

なぜ正規表現を使わないのですか?replaceAll("\\s","")すべての空白を削除します。また、\tabなどの他の非表示の記号を削除することもできます。

詳細については、docs.oracle.comをご覧ください。

于 2012-09-04T04:46:14.500 に答える
1

そして、テーマの組み合わせ...

StringBuilder result = new StringBuilder(64);
String str = "sample test";
for (Character c : str.toCharArray()) {
    if (!Character.isWhitespace(c)) {
        result.append(c);
    }
}

System.out.println(result.toString()); // toString is not required, but I've had to many people assume that StringBuilder is a String
System.out.println(str.replace(" ", ""));
System.out.println("Double  spaced".replace(" ", ""));

基本的に、新しいことは何もなく、他のすべての人が話したことの実行可能な例です...

于 2012-09-04T05:02:44.550 に答える
0
public class sample {

public static void main(String[] args) {

    String input = "sample test";
    char noSpace = ' ';
    System.out.println("String original:"+input);

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

    }
   }
于 2012-09-04T04:55:08.457 に答える
0

1 つのみで実行できる 2 つのループを保持することで、実際には行き過ぎています。

public static void main(String[] args) {
    String input = "";
    char space = ' ';

    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 char by char
        if (input.charAt(i)!= space) { // if the char is not space print it. 
            System.out.print(input.charAt(i));
        }
    }
} 
于 2012-09-04T05:02:08.133 に答える