Say I have a string, String x = "oncetherewasaboy";
I want to replace "there" with "". I tried x.replace("there",""); But this does not remove it. This is not the best example but I am doing it for an array of strings and want to clean and filter some of the information inside each index with "". Thanks!
Strings are immutable. Calling replace() doesn't change the string. It creates a new one, and returns it. You need to save the reference to it in a variable, or else you can't access it. You need:
x = x.replace("there", "");
String is an immutable Type. An immutable object is an object whose state cannot be modified after it is created. So you can not modify the string x.
So as you can not modify the string, the replace method returns a new string with the new changes. So as jlordo has already suggested you need to use like following
x = x.replace("there", "");
Related
I have a string that I define as
String string = "<html><color=black><b><center>Line1</center><center>Line2</center></b></font></html>";
that I apply to a JButton to get 2 lines of text on it, and that works perfectly. When I call the JButton.getText() method, it returns the whole string. What I want is to take the string it returns, and get the string "Line1Line2" from it. (So I want to remove all the HTML code and just get the text that appears on the screen.) I have tried using something like
if(string.contains("<html>"))
{
string.replace("<html>", "");
}
and then doing the same thing for all the other "<(stuff)>", but if I then print the string, I still get the whole thing. I think using regular expressions is a better way than to manually remove all the "<(stuff)>", but I don't know how.
Any help would be most appreciated!
string.replace() doesn't modify the string: a String is immutable. It returns a new string where the replacement has been done.
So your code should be
if (string.contains("<html>")) {
string = string.replace("<html>", "");
}
String is immutable, so String#replace does not change the String but rather returns the changed String.
string = string.replace("<html>", "");
and so on should do the thing.
String also has a replaceAll() method.
you could try string.replaceAll("<.*?>", "");
Also keep in mind that Strings in java are immutable and this operation will return a new String with your result
This question already has answers here:
String can't change. But int, char can change
(7 answers)
Closed 9 years ago.
String s1 = "ABC";
s1.replace("ABC","abc");
print(s1); // prints ABC as output
s1 = s1.replace("ABC","abc");
print(s1); //prints abc
What's the difference between two replace statements?
What happens internally when the first replace statement is called?
String.replace(CharSequence first, CharSequence second) returns a new String reference and this is why the output is different.
In the first replace line you're not assigning the resulting String to anything, whereas in the second you're replacing the reference of s1 with the result of the replacement.
s1.replace("ABC","abc"); doesn't replace on s1. It gives output of the replaced string.
$s2 = s1.replace("ABC","abc");;
print($s1); // prints ABC
print ($s2); // prints abc
Strings are immutable. It means changes are not made directly into them instead a copy of the string is created and it is changed and the reference of the changed one is returned. If you do not accept the new reference you will find the old string unchanged.
Read the API and the Java tutorials... String can NEVER be changed. That means all its methods will return a new object and your reference will still point to the old one. To assign the return to your reference, you have to assign it as in
s1 = s1.replace("ABC","abc");
Be careful with that! Quite tricky ;)
If you will change the String a lot, use StringBuffer instead... There your appends, replaces, etc have effect in the object referenced by your variable.
String.replace() Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
Code of String.replace
When you do s1.replace("ABC", "abc") imagine that in that place new string abc is created and not assigned to anything. But with s1=s1.replace("ABC", "abc") you create new string abc and assign it to the s1 variable replacing old value.
I am reading from a file line by line and then I want to check if that string contains another string so I use String.contains method but it returns always false.
I have tried to split the input line (and then using String.contains or String.equals) since the word to be checked is the first of the line.
The string I want to check is <now> and doing the splitting I have noticed that even when the line contains it I get false.
The strange fact is the string is printed out correctly but its length is bigger than the string <now>(even if I used replace to be sure there were no spaces) and I guess that is my problem. I am thinking it depends on the encoding of file but if so, is there any solution?
The file is the output of another Program (Praat) so I can not save it in another way.
line = inFile2.nextLine();
String[] w = line.split("[\t\\s]");
String checking = w[0];
checking.replace(" ","");
checking.replace("/t","");
String st ="<now>";
System.out.println(!checking.equals(st)); //returns always true
System.out.println(st.length()); //returns 5
System.out.println(checking.length()); //returns 11
System.out.println(checking); //it prints <now> correctly
The string in input is like: <now> 236 62 elena information-relation
Strings are immutable :
Note: The String class is immutable, so that once it is created a
String object cannot be changed. The String class has a number of
methods, some of which will be discussed below, that appear to modify
strings. Since strings are immutable, what these methods really do is
create and return a new string that contains the result of the
operation.
So it should be :
Checking = Checking.replace(" ","");
Checking = Checking.replace("/t","");
Or even better (method chaining) :
Checking = Checking.replace(" ","").replace("/t","");
Also please respect naming conventions.
String is immutable so you need to assign.
Checking = Checking.replace(" ","");
Checking = Checking.replace("/t","");
To make it shorter you can also do this:
String Checking = W[0].replace(" ", "").replace("/t", "");
Of course this depends on your preferences.
I solved re-saving the text file using UTF-8 encoding.
OK, this is the line I am working on:
newstring.charAt(w) += p;
trying to add a character/char (p) to the string 'newstring' at a particular position within the string which is defined by int 'w'. Is this possible?
Strings are immutable in Java, so the answer is no. But there are many ways around it. The easiest is to create a StringBuilder and use the setCharAt() method. Or insert() if you want to insert a new character at a given position.
If you make multiple modifications to your string, you can (and indeed should) reuse your StringBuilder.
Well, you can't modify your string, because Strings are immutable in Java. If you try to change the string, you will get a new string object as a result.
Now, you can use String#substring method for that, using which you can get new string which is generated by some concatenation of substring of original string.: -
str = str.substring(0, w) + "p" + str.substring(w);
But, of course, using StringBuilder as specified in #biziclop's answer is the best approach you can follow.
I have a string like :
string = abcdefghabcd
Now lets say I want to replace the first occurrence of a. I tried something like this :
string[string.indexOf('a')] = '0'
But this doesn't seems to be working. Any other way I can do this?
Thanks in advance.
In Java you can use String.replaceFirst() :
String s = "abcdefghabcd";
s = s.replaceFirst("a", "0");
System.out.println(s);
Output will be :
0bcdefghabcd
Warning : the replaceFirst() method takes a regex : so if you want to replace a special character like [ you need to escape by putting a \ before it. \ being a special character itself, you need to double it as follow :
s = s.replaceFirst("\\[", "0");
Here is the documentation on Java Regular Expressions. Also, here is Oracle's Java tutorial on manipulating Characters in Strings.
You should be aware that strings in Java are immutable. They cannot be changed. Any method you use to "change" a string will have to return a new string. If you want to modify a string directly you will need to use a mutable string type like StringBuilder.
There are many methods in the String API docs that will help you get a modified version of your string, including s.replace(), s.replaceAll(),s.replaceFirst(), ... or you could use a combination of substring and "+" to create a new string.
If you really want to treat the string as an array as in your initial example, you could use String.getChars to get an array of characters, manipulate that, and then use the String constructor String(char[]) to convert back to a String object.
In this program you will need use replaceFirst() method of String class in Java.
/*
Java String replace example.
This Java String Replace example describes how replace method of java String
class can be used to replace character or substring by new one.
*/
public class JavaStringReplaceExample{
public static void main(String args[])
{
String str="abcdefghabcd";
System.out.println(str.replaceFirst("a", "0"));
}
}
you can refer to here for details