2014-02-26 162 views
1

我有一个字符串与多个空间是不必要的,我想删除该空间,需要一个良好的结构输出。我需要在单词之间有一个空格。 INPUT:有数量后空格数,之前的第一句话。5新的生产线,与@line有一些空间[java]删除空间空间

1 





     An item one 



     area city, country 
     type of area 
     time of event 1 

2 





     An item one 



     area city, country 
     type of area 
     time of event 1 

3 ... idem 

`

,我想什么是结构只喜欢:

An item one; area city, country; type of area; time of event 1;

An item two; area city, country; type of area; time of event 2; . . .

我试着用 st.replaceAll("\n", "") 但它不是我期待.. 需要帮助..

更新部分解决和已经存在的另一个问题

  1. 问题1

     s = s.replaceAll("\\n+", " "); 
         s = s.trim(); 
         s = s.replaceAll(" \\s+", ";"); 
    

    输出:

1 An item one; area city, country; type of area; time of event 1 2 An item one; area;city, country; type of area; time of event 1

而且现在第二个问题是存在的,例如当有一个词

area city,结果给area;city,所以帮我这个存在超过1个空间...

+1

会推荐使用分隔符 – KRUKUSA

+0

失败,您的结果不符合您的原始问题。看到我的答案正确的方式。 –

+0

如果单词之间有多个空格怎么办?修剪不会删除。修剪只从右端和左端删除 – tgkprog

回答

1
public static void main(String[] args) { 
    String s= "abc  def agig"; 
    s=s.trim(); // thanks to Christian for the suggestion. 
    s= s.replaceAll("\\s+", " "); 
    System.out.println(s); 

    O/P : abc def agig 
+0

我肯定会说这个空间不是最后的或开始的。 –

+0

如果downvoters会友好地留下评论,我可以学习更多.. :) – TheLostMind

+0

@WhoAmI你试过了吗? – Christian

0

使用此为您所需的输出:

输入:

An item one 



area city, country 
type of area 
time of event 1 
下面

用途:

st = st.replaceAll("\\r?\\n+",";");

输出:

An item one;area city, country;type of area;time of event 1 
+0

结果'1; ; ; ; ; ;项目一; ; ; ;地区城市,国家;面积类型;事件1的时间; ' – enhaka

+0

@ user3145749你的输入字符串是什么? – Rahul

+0

@ user3145749你用过正则表达式中的+作为'\\ r?\\ n +'? – Rahul

0

目标是从多条线路,以分号分隔文本,然后用多余的空格去掉去?

也许你需要使用多行代码。首先摆脱额外的新线路,然后多余的空格,然后放入半冒号和连结线

所以先用单替换所有双新行:

st = st.replace("\r", "\n"); // just in case you have windows new line 
st = st.replace("\n\n",); // optional, else string tokeizer will by default iggnore consecutive seperators 

现在字符串标记,关于新的突破线

logger.info("Initial :[[[" + st + "]]]"); 
StringTokenizer st1 = new StringTokenizer (st, "\n"); 
StringBuilder sb = new StringBuilder(); //the final string, will be built here 
boolean first = true; 
while(st1.hasMoreTokens(){ 
    s = st1.nextToken(); 
    s = s.trim(); 
    s = s.replace(" ", " ");//two spaces with one 
    if(frist){ 
     first = false; 
    }else{ 
     sb.append(";"); 
    } 
    sb.append(s); 
} 
logger.info("Final :[[[" + sb + "]]]"); 

  1. 这不是编译代码,只是WR这里OTE它清晰

  2. ,如果你不使用记录你应该,或者使用的System.out.println ...

0
yourString = yourString.replaceAll("\\s+", " "); 

例如

System.out.println("abcd   ipsum   dolor \n sit.".replaceAll("\\s+", " ")); 

输出

abcd ipsum dolor sit.