Character Replacement in a String in Java - java

Currently, I have an array of Strings, each with random characters in it that are random in length. I want to replace every "A" with an "X", how would I come about doing this?
Example:
String str = "ABCDEFGAZYXW";
I want the String to become "XBCDEFGXZYXW". I tried to use:
str.replaceAll("A", "X");
But it does not change the string. Any help is greatly appreciated!

str = str.replaceAll("A", "X");
The replaceAll method doesn't change the string (strings in Java are immutable) but creates a new String object and returns it as a result of the function call. In this way we change the reference to the new object where the old one is not changed but simply not referenced.

Strings in Java are immutable, you're on the right track by using replaceAll(), but you must save the new string returned by the method somewhere, for example in the original string (if you don't mind modifying it). What I mean is:
String str = "ABCDEFGAZYXW";
str = str.replaceAll("A", "X"); // notice the assignment!

For just replacing a single character with another you can use replace:
str = str.replace('A', 'X');
As many others have already posted String.replaceAll also works, but you should be aware that the first parameter to this method is a regular expression. If you are not aware of this then it might not work as you expect in all cases:
// Replace '.' with 'X'.
str = str.replaceAll(".", "X"); // Oops! This gives "XXXXXXXXXXXX"

You have to assign the result, viz:
str = str.replaceAll("A", "X");

Try
str = str.replaceAll("A", "X");
Strings are immutable in Java.

Basically replaceAll function will take two parameter, one is string which you want to remove and second one is new string which you want to replace and its return type is String.
It will return you new string after replacement.
Here you are calling that method but not storing its new value in variable.
you can replace or print it like this
String string = "My Old String with Old value";
System.out.println(string.replaceAll("Old", "New"));
//Or
string = string.replaceAll("Old", "New");
System.out.println(string);
So in your code you should store it into your string object.
str = str.replaceAll("A", "X");

Related

How to fix ReplaceAll function in java code

i am trying to replace all occurrences of the first character in a string with another using the replace all function. However, no change occurs when i run the function. I tried to target the first character of the original string and then carry the out the replacement but no luck. Below is a snippet of my code.
public static String charChangeAt(String str, String str2) {
//str = x.xy
//str2 = d.w
String res = str.replaceAll(Character.toString(str.charAt(0)), str2);
return res ;
}
Your code replaces all characters that match the first character. If your string is abcda and you run your function, it will replace all occurences of a with whatever you put. Including the last one.
To achieve your goal you should probably not use replaceAll.
You could use StringBuilder.
StringBuilder builder = new StringBuilder(str);
myName.setCharAt(0, str2.charAt(0));
In case you want to replace all occurrences of the first character in a string with another, you can use replace instead of replaceAll. Below is the code snippet.
String str = "x.xy";
String str2 = "d.w";
String res = str.replace(Character.toString(str.charAt(0)), str2);
return res; // will output d.w.d.wy
Your function works fine but you probably are using it the wrong way.
For these strings:
String str = "abaca";
String str2 = "x";
if you do:
charChangeAt(str, str2);
this will not affect str.
You must assign the value returned by your function to str:
str = charChangeAt(str, str2);
This will change the value of str to:
"xbxcx"

Getting rid of half a String in Android

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

Java check and parse out string containing character sequence

I need to dynamically check for presence of char sequence "(Self)" in a string and parse it out.
So if my string say myString is
"ABCDEF (Self)"
it should return myString as
"ABCDEF"
What is the best way of doing it? Can it be done in a single step?
You may use the replace function as follows:
myString = myString.replace(" (Self)","");
Here, read more about things to note with String.replace or the function definition itself. Note that it is overloaded with a char variant, so you can do two kinds of things with a similar function call.
You may use the replaceAll method from the String class as follows:
myString = myString.replaceAll(Pattern.quote("(Self)"), ""));
Try following:
String test="ABCDEF (Self)";
test=test.replaceAll("\\(Self\\)", "");
System.out.println(test.trim());
Output :
ABCDEF
The dig is to use Regular Expressions for more on it visit this link.
And the code won't have a problem if there is no Self in string.
Just check out the String class' public methods.
String modifyString(String str) {
if(str.contains("(Self)")) {
str = str.replace("(Self)", "");
str = str.trim();
}
return str;
}
From the question, I understand that from source string ABCDEF (Self) also the space between F and ( should be removed.
I would recommend to use regEx if you are comfortable with it, else:
String OrigString = "ABCDEF (Self)";
String newString= OrigString.replaceAll("\\(Self\\)", "").trim();
System.out.println("New String : --" +newString+"--");
The Regular Expression for your case would be:
\s*\(Self\)\s*
Tested Java Code using regular expression would be:
String newRegExpString = OrigString.replaceAll("\\s*\\(Self\\)\\s*", "");
System.out.println("New String : -" +newRegExpString+"--");
Output:
New String : --ABCDEF--
New String : -ABCDEF--

How do I replace chars in a String at a certain location in Java?

Okay, so I have a String lets say "abcd". Now I need to be able to put bracets like this [], around a certain location. For example, if input is 0 (as in index 0), then it returns a String that holds "[a]bcd" or if the input is 2, then it returns "ab[c]d". How would I go about implementing this is Java? Is there a method in the String class already that can do this?
You can do this easily with StringBuilder:
// Note that this will need to copy things *twice*, which may be less
// efficient than just calling replace once, but it's cleaner
StringBuilder builder = new StringBuilder(text);
builder.insert(index + 1, ']');
builder.insert(index, '[');
String newText = builder.toString();
myString = new StringBuilder(myString).insert(2, '[').insert(4,']').toString();
StringBuilder is a cool class which helps to work with strings. It has insert(int index, char c) method which inserts given character to the specified location. As shown, you can create a new StringBuilder for your string, insert braces you need and convert it back to String using toString() method.
There is a replace method in String class that can do it. StringBuffer and StringBuffer also has these methods.
int index = 0;
String input = "abcd";
//System.out.println(Character.toString(input.charAt(index)));
//System.out.println("["+input.charAt(index)+"]");
String output = input.replace(Character.toString(input.charAt(index)), "["+input.charAt(index)+"]");
System.out.println(output);
Go through StringBuffer. It has got such methods.
You can use StringBuffer to do this.
String st = new String("abcd");
st = new StringBuffer(st).insert(index+1,"]").insert(index, "[").toString();

How do I split text by "," and get rid of the "," in java?

I want to split and get rid of the comma's in a string like this that are entered into a textfield:
1,2,3,4,5,6
and then display them in a different textfield like this:
123456
here is what i have tried.
String text = jTextField1.getText();
String[] tokens = text.split(",");
jTextField3.setText(tokens.toString());
Can't you simply replace the , ?
text = text.replace(",", "");
If you're going to put it back together again, you don't need to split it at all. Just replace the commas with the empty string:
jTextField3.setText(text.replace(",", ""));
Assuming this is what you really want to do (e.g. you need to use the individual elements somewhere before concatenating them) the following snippet should work:
String s1 = "1,2,3,4,5,6";
String ss[] = s1.split(",", 0);
StringBuilder sb = new StringBuilder();
for (String s : ss) {
// Use each element here...
sb.append(s);
}
String s2 = sb.toString(); // 123456
Note that the String#split(String) method in Java has strange default behavior so using the method that takes an additional int parameter is recommended.
I may be wrong, but I believe that call to split will get rid of the commas. And it should leave tokens an array of just the numbers

Categories

Resources