This question already has answers here:
String replace method is not replacing characters
(5 answers)
Closed 7 years ago.
I would like to replace "." by "," in a String/double that I want to write to a file.
Using the following Java code
double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176
System.out.println(myDouble);
String myDoubleString = "" + myDouble;
System.out.println(myDoubleString);
myDoubleString.replace(".", ",");
System.out.println(myDoubleString);
myDoubleString.replace('.', ',');
System.out.println(myDoubleString);
I get the following output
38.1882352941176
38.1882352941176
38.1882352941176
38.1882352941176
Why isn't replace doing what it is supposed to do? I expect the last two lines to contain a ",".
Do I have to do/use something else? Suggestions?
You need to assign the new value back to the variable.
double myDouble = myObject.getDoubleMethod(); // returns 38.1882352941176
System.out.println(myDouble);
String myDoubleString = "" + myDouble;
System.out.println(myDoubleString);
myDoubleString = myDoubleString.replace(".", ",");
System.out.println(myDoubleString);
myDoubleString = myDoubleString.replace('.', ',');
System.out.println(myDoubleString);
The original String isn't being modified. The call returns the modified string, so you'd need to do this:
String modded = myDoubleString.replace(".",",");
System.out.println( modded );
The bigger question is why not use DecimalFormat instead of doing String replace?
replace returns a new String (since String is immutable in Java):
String newString = myDoubleString.replace(".", ",");
Always remember, Strings are immutable. They can't change. If you're calling a String method that changes it in some way, you need to store the return value. Always.
I remember getting caught out with this more than a few times at Uni :)
Related
Need help with getting rid of half of a string in android studio. The string is:
final String strOrigin = String.valueOf(origin).trim();
The value that is returned is;
"Point{type=Point, bbox=null, coordinates=[27.993726079654873,-26.14686805145815]}"
I want to be left with only the numbers of that, in the String. I have tried;
strOrigin.replace("Point{type=Point, bbox=null, coordinates=", "");
But it isn't working. Any help would be appreciated.
In Java strings are immutable. You must assign the result to a new string:
String strResult = strOrigin.replace("Point{type=Point, bbox=null, coordinates=", "");
Make your life simpler by just getting the coordinates:
final String strOigin = origin.coordinates().stream()
.map(String::valueOf)
.collect(Collectors.joining(",","{","}"));
Or, if you're stuck on java 7:
final String strOigin = String.format(
"{%s,%s}",
String.valueOf(origin.latitude()),
String.valueOf(origin.longitude())
);
Maybe you forgot that replace() returns the result and you must assign it to a string:
String strOrigin = "Point{type=Point, bbox=null, coordinates=[27.993726079654873,-26.14686805145815]}";
String str = strOrigin
.replace("Point{type=Point, bbox=null, coordinates=", "")
.replace("}","");
System.out.println(str);
will print:
[27.993726079654873,-26.14686805145815]
This should do the trick
String s="blabla coordinates=[27.993726079654873,-26.14686805145815] ";
String requiredString = s.substring(s.indexOf("[") + 1, s.indexOf("]"));
will print:
27.993726079654873,-26.14686805145815
Than you can cast it to double or latlong format
Have a look at regular expressions, they allow you to define more flexible search patterns. In your example you only find the coordinates if the rest of the string matches the pattern exactly, but if you happen to get some other value of bbox, or even extra space it will not work. This will always match everything between a pair of square brackets:
String c = origin.replaceAll(".+?(\\[.+?\\]).+?", "$1");
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
I have a string like this:
String str="\"myValue\".\"Folder\".\"FolderCentury\"";
Is it possible to split the above string by . but instead of getting three resulting strings only two like:
columnArray[0]= "myValue"."Folder";
columnArray[1]= "FolderCentury";
Or do I have to use an other java method to get it done?
Try this.
String s = "myValue.Folder.FolderCentury";
String[] a = s.split(java.util.regex.Pattern.quote("."));
Hi programmer/Yannish,
First of all the split(".") will not work and this will not return any result. I think java String split method not work for . delimiter, so please try java.util.regex.Pattern.quote(".") instead of split(".")
As I posted on the original Post (here), the next code:
String input = "myValue.Folder.FolderCentury";
String regex = "(?!(.+\\.))\\.";
String[] result=input.split(regex);
System.out.println("result: "+Arrays.toString(result));
Produces the required output (an array with two values):
result: [myValue.Folder, FolderCentury]
If the problem you're trying to solve is really that specific, you could do it even without using regular expression matches at all:
int lastDot = str.lastIndexOf(".");
columnArray[0] = str.substring(0, lastDot);
columnArray[1] = str.substring(lastDot + 1);
This question already has answers here:
String replace method is not replacing characters
(5 answers)
Closed 6 years ago.
How do i replace the directory path of a string?
The original string is:
String fn = "/foo/bar/ness/foo-bar/nessbar.txt";
i need the output to look like:
/media/Transcend/foo-bar/nessbar.txt
I've tried the line below but it doesn't work
fn.replaceAll("/foo/bar/ness", "/media/Transcend");
You forget to rewrite variable:
String fn = "/foo/bar/ness/foo-bar/nessbar.txt";
fn = fn.replaceAll("/foo/bar/ness", "/media/Transcend");
Try this:
fn = fn.replaceAll("/foo/bar/ness", "/media/Transcend");
The replaceAll method returns a new String object, leaving the original object unmodified. That's why you need to assign the result somewhere, for example, in the same variable.
replaceAll somehow did not work for me, could not figure out why, i ended up something like this, though it replaces only first part of path.
String fn = "C:/foo/bar/ness/foo-bar/nessbar.txt";
Strign r = "C:/foo/bar/ness";
fn = "C:/media/Transcend" + fn.substring(r.length());
I am getting response for some images in json format within this tag:
"xmlImageIds":"57948916||57948917||57948918||57948919||57948920||57948921||57948 922||57948923||57948924||57948925||57948926||5794892"
What i want to do is to separate each image id using .split("||") of the string class. Then append url with this image id and display it.
I have tried .replace("\"|\"|","\"|"); but its not working for me. Please help.
EDIT: Shabbir, I tried to update your question according to your comments below. Please edit it again, if I didn't get it right.
Use
.replace("||", "|");
| is no special char.
However, if you are using split() or replaceAll instead of replace(), beware that you need to escape the pipe symbol as \\|, because these methods take a regex as parameter.
For example:
public static void main(String[] args) {
String in = "\"xmlImageIds\":\"57948916||57948917||57948918||57948919||57948920||57948921||57948922||57948923||57948924||57948925||57948926||5794892\"".replace("||", "|");
String[] q = in.split("\"");
String[] ids = q[3].split("\\|");
for (String id : ids) {
System.out.println("http://test/" + id);
}
}
I think I know what your problem is. You need to assign the result of replace(), not just call it.
String s = "foo||bar||baz";
s = s.replace("||", "|");
System.out.println(s);
I tested it, and just calling s.replace("||", "|"); doesn't seem to modify the string; you have to assign that result back to s.
Edit: The Java 6 spec says "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar." (the emphasis is mine).
According to http://docs.oracle.com/javase/6/docs/api/java/lang/String.html, replace() takes chars instead of Strings. Perhaps you should try replaceAll(String, String) instead? Either that, or try changing your String ("") quotation marks into char ('') quotation marks.
Edit: I just noticed the overload for replace() that takes a CharSequence. I'd still give replaceAll() a try though.
String pipe="pipes||";
System.out.println("Old Pipe:::"+pipe);
System.out.println("Updated Pipe:::"+pipe.replace("||", "|"));
i dont remember how it works that method... but you can make your own:
String withTwoPipes = "helloTwo||pipes";
for(int i=0; i<withTwoPipes.lenght;i++){
char a = withTwoPipes.charAt(i);
if(a=='|' && i<withTwoPipes.lenght+1){
char b = withTwoPipes.charAt(i+1);
if(b=='|' && i<withTwoPipes.lenght){
withTwoPipes.charAt(i)='';
withTwoPipes.charAt(i+1)='|';
}
}
}
I think that some code like this should work... its not a perfect answer but can help...
This question already has answers here:
String replace method is not replacing characters
(5 answers)
Closed 7 years ago.
I want the text "REPLACEME" to be replaced with my StringBuffer symbols. When I print symbols, it is a valid string. When I print my query, it still has the text REPLACEME instead of symbols. Why?
private String buildQuery(){
String query = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(REPLACEME)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
deserializeQuotes();
StringBuffer symbols = new StringBuffer();
for(int i = 0; i < quotes.size();i++){
if(i == (quotes.size()-1))
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%"); //end with a quote
else
symbols.append("%22" + quotes.get(i).getSymbol() + "%22%2C");
}
System.out.println("***SYMBOLS***" + symbols.toString());
query.replaceAll("REPLACEME", symbols.toString());
return query;
}
Change
query.replaceAll("REPLACEME", symbols.toString());
to:
query = query.replaceAll("REPLACEME", symbols.toString());
Strings in Java are designed to be immutable.
That is why replaceAll() can't replace the characters in the current string, so it must return a new string with the characters replaced.
Also if you want to simply replace literals and don't need regex syntax support use replace instead of replaceAll (regex syntax support is only difference between these two methods). It is safer in case you would want to replace literals which can contain regex metacharacters like *, +, [, ] and others.
Read the documentation :) replaceAll() returns a new String, it does replace inside the existing String. The reason for that is that Strings are immutable objects.
The String object in Java is immutable. The replaceAll will not replace the data in the string, it will generate a new string. Try this:
query = query.replaceAll("REPLACEME", symbols.toString());