How can I remove gap in String in Java - java

Here is my code:
package test;
public class Stringtest {
public static void main(String[] args) {
String a = " love y ou !! ";
String b = a.trim();
b.replaceAll("\\s+","");
System.out.println(b);
}
}
But the result is still:"love y ou !!". It just remove the white space at the start and the end of the string. Did I do anything wrong?

Strings are immutable which means you can't change them. That is why replaceAll doesn't affect original string, but creates new one with replaced values which you need to store somewhere, possibly even in original reference.
So try with
b = b.replaceAll("\\s+", "");

replaceAll method of String will return back string after removing all the spaces and as String is immutable, so assign the outcome of replaceAll back to b like:
b = b.replaceAll("\\s+","");//Note you dont need to trim if you want to replace every spaces.

Run the following and you'll understand what you have done.
System.out.println(b.replaceAll("\\s+",""));
string.replace() returns the replaced string

you forgot to store the substring which return from replaceAll method.
try
b = b.replaceAll("\\s+","");

Related

Problem with creating a replaceFirst() method in Java

Why isn't this code working?
What I'm trying to do is create a ReplaceAll() method but it is giving ArrayIndexOutOfBoundsException error.
This is Class file:
public class MyString{
private char[] data;
public MyString(){
}
public MyString(String s){
data = s.toCharArray();
}
public char replaceFirst(char o, char n){
for(int i=0; i<data.length; i++){
if(data[i]==o){
data[i]=n;
}
}
return data[n];
}
and this is my tester file:
public class Tester{
public static void main(String[] args){
MyString m1 = new MyString();
MyString m2 = new MyString("Nafees");
System.out.println(m2.replaceFirst('N','k'));
}
}
Thanks in advance.
And if I made any mistake while asking this question, sorry.
Problem is in the last line of the method:
return data[n];
n is the replacement character, but java interprets it as a number here. The n is a character "k", which is also number 107. And your input string "Nafees" doesn't have so many characters.
If you want to get the String with replaced characters, you should use this instead:
return new String(data);
P.S. You should rename the method or change implementation, because you are replacing all matching characters, not first.
You return at the end of the method data[n]. However n is the parameter (a char) of your method and not an integer. So He will convert n as an integer which will be out of the limit of your array of character.
Whilst it's great that everyone is helping diagnose and debug your code, I'd like to point out that replaceFirst is part of the standard Java String object since Java 1.4, although it does expect a regex and string instead of two char values.
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceFirst(java.lang.String,%20java.lang.String)
There is also a replaceAll method on String, if that was the intended behaviour.

How to make spaced text .equal() to unspaced text

I am working on code that takes two inputs like the following:
,Air Condition,
, Air Condition,
This text is received from a JSON object and the commas are something that must be considered.
As can be seen, one has white space at the beginning and the other doesn't. How can I compare them using the equals()?
So far, I have used the following code to compare the two strings:
if (oldSelected.get(i).equalsIgnoreCase(String.valueOf(fc.getText()))){
fc.setChecked(true);
}
However, it doesn't do what I expect it to do.
How i can trim this space and get the desired results?
You need to trim the white spaces first.
String oldSelected = ",Air Conditioner,";
String newSelected = ", Air Conditioner, ";
if(oldSelected.replaceAll("\\s", "").equalsIgnoreCase(newSelected.replaceAll("\\s", ""))){
// Do Something
}
else{ // Do Something Else
}
Hope that helps! :)
You can do something like this:
public static void main(String[] args) {
String s1 = ",Air Condition";
String s2 = ", Air Condition";
System.out.println(s1.equals(s2.replace(", ", ",")));
}
or, if you want to keep space between words, you may use like this:
public static void main(String[] args) {
String s1 = ",Air Condition";
String s2 = ", Air Condition";
System.out.println(s2.split(", ")[1]);
System.out.println(s1.split(",")[1]);
System.out.println(s1.split(",")[1].equals(s2.split(", ")[1]));
}
Try,
String.valueOf(fc.getText())).replaceAll("\\s+","")
This removes all whitespaces and non-visible characters (e.g. tab, \n)
you can use String methot called SPLIT for example you have
String STR1 = "Ahoj"
String STR2 = "Ahoj "
String x[] = STR1.split(" ");
String y[] = STR2.split(" ");
then use simple for loop to check all words :)
Well, worked solution as #Rahul suggest to use .trim() but this worked with english words only, so in order to equalize all language i trim the equalized text to as below :
String checkedVal = oldSelected.get(i);
checkedVal = checkedVal.trim();
if (checkedVal.equalsIgnoreCase(String.valueOf(fc.getText().toString().trim()))){
fc.setChecked(true);
}
Thanks for all answers.

Java .replace() seems to modify an array [duplicate]

I'm doing something like
public static String[] list = {"a","b","c","d",} //It gives me a NullPointeException if I didn't use static
public String encrypt(String a){
a = a.replace(list[0],list[2]);
a = a.replace(list[4],list[3]);
return a;
}
and I have another method that just reverses it
public String decrypt(String a){
a = a.replace(list[2],list[0]);
a = a.replace(list[3],list[4]);
return a;
}
Of course this is simplified, the real code I'm using uses the entire alphabet and some numbers. So here's my problem: If I input something like 123 into encrypt() and it outputs ngV then I input ngV into decrypt() it gives me like 1q3. Only some of the letters are correctly switched and some aren't. Is there something with the replace() method using array values that I'm missing? I'm obviously new to Java.
Also I read Java replace() problems but replaceAll() didn't work out.
I suspect your question is "why is chaining .replace acting oddly" and the array is not changing. You can prove that replace does not change the array quite easily:
System.out.println(Arrays.toString(list));
encrypt("abc");
System.out.println(Arrays.toString(list));
So what is going on with your code? Each time you replace a letter you end up with a new string, that again you replace letters on. I don't have your full source code so I'll show with a real simple version:
a = a.replace("a", "b");
a = a.replace("b", "c");
a = a.replace("c", "d");
For "abc" is.... 'ddd'.
The answer to this is to look at each letter at a time and change it. Loop through the string and create a new one.

Remove all numbers and "{" from a String Array

I am trying to remove all non numeric characters from the String Array as require to compare it with the list of numbers. The split works but I am not able to compare the two Sets
for(String w:a1)
{
w=w.replaceAll("[^\\d.]", "");
if(dContacts.getNumber().equals(w))
{
System.out.println("Compared1234567");
}
System.out.println("---6545678909876789876hijkhijkhijkjh"+dContacts.getNumber());
System.out.println("Arraylistextract"+w);
}
In Java, Strings are immutable. This means that w.replaceAll("[^\\d.]", ""); will create a different String, and w will remain the same. Assign that expression to w to store it:
w = w.replaceAll("[^\\d.]", "");
You cannot modify a string without reassigning it to either the same variable or a new one.
String is Immutable so if you are calling some function then it will not change in same object.
you have to change this line to
w= w.replaceAll("[^\\d.]", "");

how to replace some chars in the string with other chars by the user?

I wrote a text, and i want to change some chars to any other chars which the user will choosing them, I tried and couldn't find the correct answer, so please guide me.
the code in the MyTest Class is:
public String replace(String input,char from,char to){
String input2 ="";
String input3="";
this.input=input3;
for(int i=0;i<input.length();i++){
for(int j=0;j<input3.length();j++){
if(input.charAt(i)==input3.charAt(j)){
input2=input3.replace(from, to);
System.out.println(input2);
}
}
}
return input2;
}
And the code in the Main Class:
System.out.println("please enter the new character: ");
char c1 = scan.next().charAt(0);
System.out.println("Please choose the letters that you want to change it which in the text:");
String ltr = scan.next();
obj1.convertChars(ltr, c1);
(1) What you should do:
There is a simple method for what you are after: String#replace(char,char):
String replaced = myString.replace(from,to);
(2) Why your code fails:
Note you are iterating and trying to invoke replace() on input3, while it is an empty string! you never changed it! effectively your method do nothing (except assigning the instance variable input. Definetly not what you wanted.
(3) Also important: Strings in java are immutable
In java, String is immutable - so what you are doing is actually crating a new string with replaced characters, and NOT replacing the characters in the same string object!
Changing the String is not as simple, and should be avoided, but can be done using the reflection API.
What you want to do shouldn't even be a method. Here's why:
public String replace(String input,char from,char to){
return input.replace(from, to);
}
Thus kind of method adds no value - you should just call the replace() method of String directly.
The question seemed a bit unclear. I hope you want a function like this:
Call this function from the main function. Pass the string "abcde", 'a', 'x'. It will return you "xbcde".
public String replace(String inputStr, char from, char to){
StringBuffer newString=new StringBuffer();
for(int i=0;i<inputStr.length();i++){
if(inputStr.charAt(i)==from){
newString.append(to);
}
else{
newString.append(inputStr.charAt(i));
}
}
return newString.toString();
}

Categories