I have a program that is reading a text file that has a list of items, creates an ArrayList consisting of the items it reads, then compares it to a few chosen words. For example, my text file contains this (without the numbering):
book
desk
food
phone
suit
and it reads each one and adds it to an ArrayList. When I tried comparing a String s = "book" to each element in the ArrayList, I find that s is not equal to anything. This is what I have in a method:
for (int i = 0; i < list.size(); i++)
{
if (s.equals(list.get(i))
return true;
}
s.contains() doesn't work either. When I print the ArrayList, there's an additional whitespace at the end of each String element. How can I get the comparison to work when s = "book"? Why is there additional whitespace?
Use trim() to remove leading and trailing whitespace.
if (s.equals(list.get(i).trim())
return true;
}
instead of
if (s.equals(list.get(i))
return true;
}
You can use the trim() method of the String class to remove whitespaces in the start and the end of the string.
The whitespaces may be in the file but you didn't notice it. Check with an editor that there are no spaces at the end. To be more sure, check with a hexadecimal editor like hd on unix.
Also, check that the read strings do not contain the line feed character.
Related
How to create a method that will take imput of a String and an integer n and output the String divided into parts consisting of n characters and separated by a blank space? For example, imput String: "THISISFUN", integer:3, result: "THI SIS FUN".
When you answer, can you please really try to explain what each part of the code does? I really want to understand it.
I tried using StringBuilder and the split() method but the problem is that I don't understand how all of that works. Therefore, I ended up kind of thoughtlessly pasting parts of codes from different online articles which doesn't work the best if you want to actually learn something, especially if you simply cannot find any posts about a specific issue. I could only find things like: "how to divide the String into n parts" and "how to ad a space after a specific char" which are sort of similar issues but not the same.
Here is one way to do it:
public static void splitString(String str, int groupSize){
char[] arr = str.toCharArray(); // Split the string into character array ①
// Iterate over array and print the characters
for(int i=0; i<arr.length; i++){
// If 'i' is a multiple of 'groupSize' ②
if(i > 0 && i % groupSize == 0){ ③
System.out.print(" ");
}
System.out.print(arr[i]);
}
}
① Split the string into a character array (so that you can access the characters individually). You can also do it using the charAt() method without splitting the string into an array. Read the Javadoc for more details.
② Check if the loop counter i is a multiple of groupSize
③ Note the use of System.out.print() as we do not want to print a newline. Here you can use a StringBuilder too and print the contents at the end instead of printing the characters inside the loop.
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 a problem with a contains (...) method from List <...> class. I'm trying to check if a expression (that is loaded from user input) already exist in a List, but if I entered same name as twice, it said there's nothing same in the List. Please help, there's source code:
boolean checker;
checker = expressions.contains(line[1]);
if (checker == true) {
System.err.println("This expression has already been declared!");
return index;
}
PS: line[1] is a second index in array from main function that stores user-entered line split by whitespaces. (First index of line need to be always 'var', and second is any word that cannot be twice in the List)
Your list may not have exact same string as provided in the input which may be due to white spaces. Try trimming the input and then call contains
checker = expressions.contains(line[1].trim());
I have an array list named myArraylist that contains items of the class named TStas. Tstas has a string variable named st_name. I want to search the array list, looking for the TStas instance whose st_name is equal to the string look for and when found return the position (found places) of the TStas in the array list.
public static List<Integer> findplace_byname(String lookfor){
List<Integer> foundplaces = new ArrayList<>(); //list to place posistions of found items
for(int k=0; k<myArraylist.size(); k++) {
TStas a=myArraylist.get(k);
JOptionPane.showMessageDialog(null, "#"+a.st_name+"#"+lookfor+ "#"); //just to check if everything is read,
if ((a.st_name).equals(lookfor)){
foundplaces .add(k);
}
}
return foundplaces;
}
My problem is that the code fails to detect the equality when comparing to the a.st_name of the first item in myArraylist.
For example:
if I have in myarrailist an item with a.st_name=S9, an item with a.st_name=K9 and another with a.st_name=G4. When lookfor is K9 or G4 all is ok. When searching for the first item in the array having a.st_name=S9 the code fails to "see" the equality.
I am using the showMessageDialog to check that the variable is realy read and it is so. Also I tried to delete or change the 1st item in the arraylist, but the same problem goes on: The 1rst item is not found.
What is happening here?
EDIT
I used the trim() to remove any possible spaces but nothing changed. I then used .length() on the "trimed" string to get the length of each string to be compared and I found that for some reason the 1st element while being "S9" without any spaces has a length of 3!! Is it possible that some king of character is hidden? (I have no idea, a paragraph character or what?)
There is no issue in your current code, check this code your self.
List<Integer> foundplaces = new ArrayList<>();
List<String> myArraylist=new ArrayList<>();
myArraylist.add("S9");
myArraylist.add("K9");
myArraylist.add("G4");
for(int k=0; k<myArraylist.size(); k++) {
String a=myArraylist.get(k);
JOptionPane.showMessageDialog(null, "#" + a + "#" + "S9" + "#");
if ((a).equals("S9")){
foundplaces .add(k);
System.out.println(k);
}
}
You can see it is working fine. same as your current code.
I found where the problem is.
As I mentioned is a comment I am using a txt file to populate myarraylist . Windows notepad ads automatically to the beginning of text files a BOM character.
(http://en.wikipedia.org/wiki/Byte_Order_Mark.). This character is the problem because I may read "S9" (the first text in the txt file) but it actually is the \65279 character plus "S9".
So using the following when reading the text file that is used to populate myarraylist the problem is solved.
if((int)readingstring.charAt(0)==65279){
readingstring=readingstring.substring(1);
}
Thanks for your help.
I have this code which searches a string array and returns the result if the input string matches the 1st characters of a string:
for (int i = 0; i < countryCode.length; i++) {
if (textlength <= countryCode[i].length()) {
if (etsearch
.getText()
.toString()
.equalsIgnoreCase(
(String) countryCode[i].subSequence(0,
textlength))) {
text_sort.add(countryCode[i]);
image_sort.add(flag[i]);
condition_sort.add(condition[i]);
}
}
}
But i want to get those string also where the input string matches not only in the first characters but also any where in the string? How to do this?
You have three way to search if an string contain substring or not:
String string = "Test, I am Adam";
// Anywhere in string
b = string.indexOf("I am") > 0; // true if contains
// Anywhere in string
b = string.matches("(?i).*i am.*"); // true if contains but ignore case
// Anywhere in string
b = string.contains("AA") ; // true if contains but ignore case
I have not enough 'reputation points' to reply in the comments, but there is an error in the accepted answer. indexOf() returns -1 when it cannot find the substring, so it should be:
b = string.indexOf("I am") >= 0;
Check out the contains(CharSequence) method
Try this-
etsearch.getText().toString().contains((String) countryCode[i]);
You could use contains. As in:
myString.contains("xxx");
See also: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html, specifically the contains area.
Use the following:
public boolean contains (CharSequence cs)
Since: API Level 1
Determines if this String contains the sequence of characters in the CharSequence passed.
Parameters
cs the character sequence to search for.
Returns
true if the sequence of characters are contained in this string, otherwise false
Actually, the default Arrayadapter class in android only seems to search from the beginning of whole words but by using the custom Arrayadapter class, you can search for parts of the arbitrary string. I have created the whole custom class and released the library. It is very easy to use. You can check the implementation and usage from here or by clicking on the link provided below.
https://github.com/mohitjha727/Advanced-Search-Filter
You can refer to this simple example-
We have names " Mohit " and "Rohan" and if We put " M" only then Mohit shows up in search result, but when we put "oh" then both Mohit and Rohan show up as they have the common letter 'oh'.
Thank You.