2012-09-04 21 views
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中,任何建議將是巨大的感謝!

+0

什麼是你的問題只是運行的例子嗎? – maba

+1

通過使用Character.isWhitespace()簡化... http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#isWhitespace(char) – Adam

+2

個人而言,我會考慮使用[regex](http://docs.oracle.com/javase/tutorial/essential/regex/intro.html)。示例:'sText = sText.replaceAll(「\\ s +」,「」);' – paulsm4

回答

1

爲什麼你不使用正則表達式? replaceAll("\\s","")刪除所有空格。你還可以去除其他不可見的符號,如\標籤等

docs.oracle.com更多信息

+0

我很清楚其他更快的選擇,比如你提到的那個。我試圖通過這種特定的方式來更好地理解循環和計數器。 –

+0

不要忘記,空白區域可能包含諸如選項卡 – MadProgrammer

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

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

+1之類的內容,以便使用「isWhiteSpace」 – MadProgrammer

0

你實際上已經走得太遠通過保持兩個循環,你能做到這一點的只有一個:

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)); 
     } 
    } 
} 
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(" ", "")); 

基本上沒有什麼新的,什麼每個身體其他人已經談過......