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.]", "");
Related
I have a string which is :
1|name|lastname|email|tel \n
2|name|lastname|email|tel \n
I know that I have to use a loop to display all lines but the problem is that in my assignment
I can't use arrays or other classes than String and System.
Also I would like to sort names by ascending order without using sort method or arrays.
Do I have to use compareTo method to compare two names ?
If that's the case, how do I use compareTo method to sort names.
For example, if compareTo returns 1, that means that the name is greater than the other one. In that case how do I manage the return to sort name properly in the string ?
To display all substrings of the string as in the example, you can just go through all characters one by one and store them in a string. Whenever you hit a delimiter (e.g. | or \n), print the last string.
Here's a thread on iterating through characters of a string in Java:
What is the easiest/best/most correct way to iterate through the characters of a string in Java?
If you also need to sort the names in ascending order without an array, you will need to scan the input many times - sorting N strings takes at least N*log(N) steps. If this is a data structure question, PriorityQueue should do the trick for you - insert all substrings and then pop them out in a sorted fashion :)
building on the previous answer by StoneyKeys, since i do not have the privilege to comment, you can use a simple if statement that when the char is a delimiter, System.out.println() your previous scanned string. Then you can reset the string to an empty string in preparation for scanning the next string.
In java, there are special .equals() operators for strings and chars so when you won't be using == to check strings or char. Do look into that. To reset the value of string just assign it a new value. This is because the original variable points at a certain string ie "YHStan", by making it point at "", we are effectively "resetting" the string. ie scannedstr = "";
Please read the code and understand what each line of code does. The sample code and comments is only for your understanding, not a complete solution.
String str ="";
String value = "YH\nStan";
for (int i=0; i <value.length(); i++) {
char c = value.charAt(i);
String strc = Character.toString(c);
//check if its a delimiter, using a string or char .equals(), if it is print it out and reset the string
if (strc.equals("\n")) {
System.out.println(str);
str ="";
continue; // go to next iteration (you can instead use a else if to replace this)
}
//if its not delimiter append to str
str = str +strc;
//this is to show you how the str is changing as we go through the loop.
System.out.println(str);
}
System.out.println(str); //print out final string result
This gives a result of:
Y
YH
YH
S
St
Sta
Stan
Stan
I have two strings and I am trying to copy one into another. How I can copy character by character a string into another in Java?.
Strings are immutable objects in Java, which means that after they are instantiated, they will not change internal state. Instead, if you want to modify a String, you will always get a new String.
Now, to your question. If you want to copy a String chararcter by character this is highly inefficient, since you would create a new String object each time you copy a character. Luckily, there are plenty of other options.
String a = "a";
String b = "b";
String c = a + b; // "ab"
String d = a.concat(b); // "ab"
If you simply want to copy a String, you can do the following:
String e = a; "a"
Why does that work? As stated earlier, Strings a immutable, thus a new String with the same content is created. You can think of it as String e = new String(a), which is slightly less performant (and therefore an antipattern), but also works.
Take user input for 5 times, store them in a variable and display all 5 values in last. How can I do this in Java? Without using arrays, collections or database. Only single variable like String and int.
Output should look like this
https://drive.google.com/file/d/0B1OL94dWwAF4cDVyWG91SVZjRk0/view?pli=1
This seems like a needless exercise in futility, but I digress...
If you want to store them in a single string, you can do it like so:
Scanner in = new Scanner(System.in);
String storageString = "";
while(in.hasNext()){
storageString += in.next() + ";";
}
if you then input foo bar baz storageString will contain foo;bar;baz;. (in.next() will read the input strings to the spaces, and in.hasNext() returns false at the end of the line)
As more strings are input, they are appended to the storageString variable. To retrieve the strings, you can use String.split(String regex). Using this is done like so:
String[] strings = storageString.split(";");
the strings array which is retrieved here from the storageString variable above should have the value ["foo", "bar", "baz"].
I hope this helps. Using a string as storage is not optimal because JVM creates a new object every time a string is appended onto it. To get around this, use StringBuilder.
*EDIT: I originally had said the value of the strings array would be ["foo", "bar", "baz", ""]. This is wrong. The javadoc states 'Trailing empty strings are therefore not included in the resulting array'.
public static void main(String[] args) {
String s = "";
Scanner in = new Scanner(System.in);
for(int i=0;i<5;i++){
s += in.nextLine();
}
System.out.println(s);
}
Why dont you use Stingbuilder or StringBuffer, keep appending the some delimiter followed by the input text.
Use simple String object and concatenate it with new value provided by user.
String myString = "";
// while reading from input
myString += providedValue;
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+","");
I am using eclipse with java
I am trying to compare two string removing all the space between them.
Here is my code
First I am removing whitespace within the Strings.
System.out.println("["+StringUtils.deleteWhitespace(s4)+"]");
System.out.println("["+StringUtils.deleteWhitespace(s3)+"]");
// comparing Strings
if(s4.equals(s3))
{
System.out.println("Text Match");'
}
Below is the output from lines 1 and 2 that is displaying on Eclipse console:
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
[gnarlyadj.Somethingthatisgnarlyhasmanyknotsandbumpyareasonitssurface.nudosoadj.Algonudosotienemuchosnudosyunasuperficiellenadebultos.]
From what I can see, there is no difference between two string yet it is displaying string as a mismatch.
You did not assign the results of the deleteWhitespace() operation to anything. Your two strings will therefore remain unchanged.
Store the result like so, before printing it:
s4 = StringUtils.deleteWhitespace(s4);
The method StringUtils.deleteWhitespace(s4) does not change the String referenced by s4 (Strings are immutable) but returns a new string.
If you do the following code:
s3 = StringUtils.deleteWhitespace(s3);
s4 = StringUtils.deleteWhitespace(s4);
if (s4.equals(s3)) {
System.out.println("Text Match");'
}
Then you will see that the two strings are really equal and the "Text Match" is printed.