简单的空间修剪程序

时间:2015-12-17 08:19:11

标签: java arrays java.util.scanner

我有这个java代码来修剪字符串中的所有空格。

import java.util.Scanner;
import java.util.Arrays;

public class trimSpace {
   public static void main( String[] args ) {

   Scanner input = new Scanner(System.in);

   String str;

   System.out.print("Please enter a string:");
   str = input.nextLine();

   System.out.println("The result is : ");

   char[] charArray = new char[A.length()];
   for(int i=0;i<A.length();i++){
      if (A.charAt(i) != ' ') { //This line should ignore the space in the str
        charArray[i] = A.charAt(i); 
        System.out.print(charArray[i]);
      }     
   }
   //Expected output [j,a,v,a,,,]
   System.out.println(Arrays.toString(charArray)); //Output [j," ",A," ",V," ",A]
   }
}

如果我插入&#34; J A V A&#34;在str中,charArray仍然包括打印后的空格,即[j,&#34; &#34;,A,&#34; &#34;,V&#34; &#34;,A]我在这里做错了什么?

2 个答案:

答案 0 :(得分:2)

您将“正确的字符”放入找到它们的相同索引中。这样你跳过空格并留下它们。

    charArray[i] = A.charAt(i); 
    System.out.print(charArray[i]);

您需要在counter中添加charArray

    charArray[counter++] = A.charAt(i);

如果输入一个空格,那么你只会在charArray前进。或者更完整:

  int counter = 0;
  for(int i=0;i<A.length();i++){
  if (A.charAt(i) != ' ') { //This line should ignore the space in the str
    charArray[counter++] = A.charAt(i); 
  }     

答案 1 :(得分:0)

你可以试试这个:

String str = "J A V A";
str = str.replaceAll("\\s+", "");