2013-02-17 151 views
2

如何刪除字符串之外的所有空格「」? 例如:刪除字符串「」之外的空格

0507 ? "Y e a" : "No" 

應返回:

0507?"Y e a":"No" 

謝謝。

+0

請閱讀:http://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java – user1428716 2013-02-17 03:41:47

+0

嗨,呃,我已經讀過了,但是......沒有結果。我知道如何替換字符串中的所有空格,但我不知道如何只替換引號之外的空格。 – BloodShura 2013-02-17 03:43:57

回答

3

嘗試

String s = "0507 ? \"Y e a\" : \"No\"".replaceAll(" +([?:]) +", "$1"); 
    System.out.println(s); 

打印

0507?"Y e a":"No" 
+0

謝謝Evgeniy! – BloodShura 2013-02-17 04:02:50

1

- 您可以通過 「使用st.split()函數

- 然後應用st.replaceAll分割(」 \ S」, 「」)只在陣列

- 然後concate的偶數索引陣列的使用各種UTILITES(所有元素如Apache Commons Lang中StringUtils.join

如:

原來的字符串 - 0507 「Y EA」: 「否」

與「..... {0507? ,Y e a,:,No}

對陣列的偶數索引應用st.replaceAll(「\ s」,「」).... {0507} ,Y EA,:,無}

Concate使用StringUtils.join(S, 「\」 「)...... 0507 」Y EA「:」 否」

示例代碼:

String input="0507 ? \"Y e a\" : \"No\""; 
    String[] inputParts = input.split("\""); 

    int i = 0; 
    while(i< inputParts.length) 
    { 
     inputParts[i]=inputParts[i].replaceAll("\\s", ""); 
     i+=2; 
    } 

    String output = StringUtils.join(inputParts, "\""); 
+0

謝謝,阿米特! :D – BloodShura 2013-02-17 04:03:18

1

或嘗試StringTok enizer:讀tokenizer使用默認分隔符集,即「\ t \ n \ r \ f」:空格字符,製表符,換行符,回車符和換頁符。

StringTokenizer tok=new StringTokenizer(yourString); 
    String temp=""; 

    while(tok.hasMoreElements()){ 
     temp=temp+tok.nextElement(); 
    } 

    System.out.println("temp"+temp); 
+0

嘗試任何最有效的算法(算法明智) – user1428716 2013-02-17 04:01:32

+0

呃...但我認爲這會改變100? 「y e a」:「n o」in:100?「yea」:「no」,我只需要在引號(「)e.e外刪除空格。但是,無論如何,謝謝! – BloodShura 2013-02-17 04:05:03

1

此代碼

static Pattern groups = Pattern.compile("([^\\\"])+|(\\\"[^\\\"]*\\\")"); 
public static void main(String[] args) { 
    String test1="0507 ? \"Y e a\" : \"No\""; 
    System.out.println(replaceOutsideSpace(test1)); 
    String test2="0507 ?cc \"Y e a\" :bb \"No\""; 
    System.out.println(replaceOutsideSpace(test2)); 
    String test3="text text text text \"Y e a\" :bb \"No\" \"\""; 
    System.out.println(replaceOutsideSpace(test3)); 
    String test4="text text text text \"Y e a\" :bb \"No\" \"\" gaga gag ga end"; 
    System.out.println(replaceOutsideSpace(test4)); 
} 
public static String replaceOutsideSpace(String text){ 
    Matcher m = groupsMatcher(text); 
    StringBuffer sb = new StringBuffer(text.length()); 
    while(m.find()){ 
     String g0=m.group(0); 
     if(g0.indexOf('"')==-1){g0=g0.replaceAll(" ", "");} 
     sb.append(g0); 
    } 
    return sb.toString(); 
} 
private synchronized static Matcher groupsMatcher(String text) 
{return groups.matcher(text);} 

打印

0507?"Y e a":"No" 
0507?cc"Y e a":bb"No" 
texttexttexttext"Y e a":bb"No""" 
texttexttexttext"Y e a":bb"No"""gagagaggaend