2015-04-07 68 views
-1

我需要格式化字符串,由冒号分隔和分号(具体如何只替换Java中的某些字符?

Apartment or Building Number;Street Address:City:State Postal Code (i.e. NY):Zip Code 

,并把它改为

Apartment or Building Number 
Street Address 
City, State Zip Code 

到目前为止,我有

public class MultiLine { 
public static void main(String[] args) { 
    Scanner input = new Scanner(System.in); 

    System.out.print("Please enter an address formatted as such: 'Apartment or Building Number" 
      + ";Street Address:City:State Postal Code (i.e. NY):Zip Code' \nFor example, Building Room 012;123 Fake Lane:Somewhere:NC:28500 \nPlease enter your address now: "); 
    String text = input.nextLine(); 
    String text1 = text.replace(';', '\n'); 
    String text2 = text1.replace(':', '\n'); 

    System.out.print(text2); 

     } 

} 

这但是,它并不能真正起作用,因为它会用一条新线代替所有的冒号,当我只想要1被替换时,我不完全确定如何使用replaceFirst,因为每次我使用它,它说我不能将字符转换为字符串,但这显然不是replace的问题。我不能分割字符串,主要是因为我没有覆盖。 (我也没有覆盖的replace命令,但它似乎最有意义。)我也有不知道如何使用regex

+0

字符串'State Postal Code(ie NY)'?我以前已经问过你这个问题。 –

+0

'replaceFirst'需要一个正则表达式,而不是一个字符。但是,由于':'和';'在正则表达式中不是特殊字符,因此可以简单地使用一个字符的字符串,例如'text.replaceFirst(“;”,“\ n”);',它会起作用。对于特殊的字符,您必须包含反斜杠(并且您必须反斜杠反斜杠),例如'text.replaceFirst(“\\。”,“\ n”);'如果你想替换句点字符。 – ajb

+0

它仍然在那里,Avinash拉杰。我只是将它缩短为“国家” –

回答

0

看到replaceFirst请求字符串,这样你就可以以这种方式使用它:

text.replaceFirst(";", "\n") 
+0

哦,所以我不得不用引号替换撇号? –

+0

“带引号的撇号”,我不明白 –

+0

我有text.replaceFirst(';','\ n'),并没有工作,但我将它改为text.replaceFirst(“;”,“ \ n“),那有效,换句话说,我把'(撇号)改为”(引号) –

0
public static void main(String[] args) { 
    String text = "Apartment or Building Number;Street Address:City:State Postal Code (i.e. NY):Zip Code"; 
    String text1 = text.replace(';', '\n'); 
    String text2 = text1.replaceFirst(":", "\n"); 

    System.out.print(text2); 
}