从String中删除“”之外的空格

时间:2013-02-17 03:35:50

标签: java string char token stringtokenizer

如何删除String上“?”之外的所有空格? 例如:

0507 ? "Y e a" : "No"

应该返回:

0507?"Y e a":"No"

谢谢。

4 个答案:

答案 0 :(得分:3)

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

打印

0507?"Y e a":"No"

答案 1 :(得分:1)

- 您可以通过“使用st.split()函数

进行拆分

- 然后仅对数组的偶数索引应用st.replaceAll(“\ s”,“”)

- 然后使用各种实用程序(如Apache Commons lang StringUtils.join(

)来连接数组的所有元素

<强>例如

原始字符串 - 0507? “是的”:“不”

用“..... {0507?,Y e a,:,No}

分开后

在数组的偶数索引上应用st.replaceAll(“\ s”,“”).... {0507? ,是,a,:,No}

使用StringUtils.join(s,“\”“)...... 0507结束?”是的“:”否“

示例代码:

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

答案 2 :(得分:1)

或尝试StringTokenizer:读取tokenizer使用默认分隔符集,即“\ t \ n \ r \ n”:空格字符,制表符,换行符,回车符,以及换页字符。

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

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

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

答案 3 :(得分: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
相关问题