我需要格式化一个字符串,用冒号和分号分隔(具体来说,
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
,因为每次我使用它时,它都表示我无法将char转换为字符串,但这显然不是replace
的问题。我不能分割字符串,主要是因为我根本没有覆盖它。 (我也没有涉及replace
命令,但似乎最有意义。)我也不知道如何使用regex
答案 0 :(得分:0)
请参阅replaceFirst请求字符串,因此您可以这样使用它:
text.replaceFirst(";", "\n")
答案 1 :(得分: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);
}