I am unable to replace part of the substring in my code ? I want to get rid of the unwanted characters but i still get the same output ?
String BusDetails = "ROUTE 3 — CLEARBROOK-UFV GOLINE TO UFV" ;
System.out.println("BusDetails before"+BusDetails);
BusDetails.replaceAll("—", "");
System.out.println("BusDetails After"+BusDetails);
// Output
BusDetails before ROUTE 3 — CLEARBROOK-UFV GOLINE TO UFV
BusDetails After ROUTE 3 — CLEARBROOK-UFV GOLINE TO UFV
asked Feb 20, 2014 at 5:45
dev_marshell08
1,1114 gold badges19 silver badges43 bronze badges
3 Answers 3
Java strings are immutable. You need to do this:
BusDetails = BusDetails.replaceAll("—", "");
Also: "standard practice" is to name variables with a lowercase first letter busDetails.
answered Feb 20, 2014 at 5:47
John3136
29.3k4 gold badges55 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
BusDetails= BusDetails.replaceAll("—", "");
you forgot to re assign variable
answered Feb 20, 2014 at 5:47
Yogesh
4,8443 gold badges36 silver badges44 bronze badges
Comments
You need to put 'replaced value' into another variable. Example below compiled code:
String busDetails = "ROUTE 3 — CLEARBROOK-UFV GOLINE TO UFV" ;
System.out.println("BusDetails before :"+busDetails);
String replacetxt = busDetails.replaceAll("— ", "");
System.out.println("BusDetails After :"+replacetxt);
answered Feb 20, 2014 at 5:58
Suzon
7591 gold badge8 silver badges21 bronze badges
Comments
lang-java
BusDetails.replaceAll("—", "");toBusDetailsBusDetailsshould be namedbusDetails.