Java contains method - java

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());

Related

finding the middle index of a substring when there are duplicates in the string

I was working on a Java coding problem and encountered the following issue.
Problem:
Given a string, does "xyz" appear in the middle of the string? To define middle, we'll say that the number of chars to the left and right of the "xyz" must differ by at most one
xyzMiddle("AAxyzBB") → true
xyzMiddle("AxyzBBB") → false
My Code:
public boolean xyzMiddle(String str) {
boolean result=false;
if(str.length()<3)result=false;
if(str.length()==3 && str.equals("xyz"))result=true;
for(int j=0;j<str.length()-3;j++){
if(str.substring(j,j+3).equals("xyz")){
String rightSide=str.substring(j+3,str.length());
int rightLength=rightSide.length();
String leftSide=str.substring(0,j);
int leftLength=leftSide.length();
int diff=Math.abs(rightLength-leftLength);
if(diff>=0 && diff<=1)result=true;
else result=false;
}
}
return result;
}
Output I am getting:
Running for most of the test cases but failing for certain edge cases involving more than once occurence of "xyz" in the string
Example:
xyzMiddle("xyzxyzAxyzBxyzxyz")
My present method is taking the "xyz" starting at the index 0. I understood the problem. I want a solution where the condition is using only string manipulation functions.
NOTE: I need to solve this using string manipulations like substrings. I am not considering using list, stringbuffer/builder etc. Would appreciate answers which can build up on my code.
There is no need to loop at all, because you only want to check if xyz is in the middle.
The string is of the form
prefix + "xyz" + suffix
The content of the prefix and suffix is irrelevant; the only thing that matters is they differ in length by at most 1.
Depending on the length of the string (and assuming it is at least 3):
Prefix and suffix must have the same length if the (string's length - the length of xyz) is even. In this case:
int prefixLen = (str.length()-3)/2;
result = str.substring(prefixLen, prefixLen+3).equals("xyz");
Otherwise, prefix and suffix differ in length by 1. In this case:
int minPrefixLen = (str.length()-3)/2;
int maxPrefixLen = minPrefixLen+1;
result = str.substring(minPrefixLen, minPrefixLen+3).equals("xyz") || str.substring(maxPrefixLen, maxPrefixLen+3).equals("xyz");
In fact, you don't even need the substring here. You can do it with str.regionMatches instead, and avoid creating the substrings, e.g. for the first case:
result = str.regionMatches(prefixLen, "xyz", 0, 3);
Super easy solution:
Use Apache StringUtils to split the string.
Specifically, splitByWholeSeparatorPreserveAllTokens.
Think about the problem.
Specifically, if the token is in the middle of the string then there must be an even number of tokens returned by the split call (see step 1 above).
Zero counts as an even number here.
If the number of tokens is even, add the lengths of the first group (first half of the tokens) and compare it to the lengths of the second group.
Pay attention to details,
an empty token indicates an occurrence of the token itself.
You can count this as zero length, count as the length of the token, or count it as literally any number as long as you always count it as the same number.
if (lengthFirstHalf == lengthSecondHalf) token is in middle.
Managing your code, I left unchanged the cases str.lengt<3 and str.lengt==3.
Taking inspiration from #Andy's answer, I considered the pattern
prefix+'xyz'+suffix
and, while looking for matches I controlled also if they respect the rule IsMiddle, as you defined it. If a match that respect the rule is found, the loop breaks and return a success, else the loop continue.
public boolean xyzMiddle(String str) {
boolean result=false;
if(str.length()<3)
result=false;
else if(str.length()==3 && str.equals("xyz"))
result=true;
else{
int preLen=-1;
int sufLen=-2;
int k=0;
while(k<str.lenght){
if(str.indexOf('xyz',k)!=-1){
count++;
k=str.indexOf('xyz',k);
//check if match is in the middle
preLen=str.substring(0,k).lenght;
sufLen=str.substring(k+3,str.lenght-1).lenght;
if(preLen==sufLen || preLen==sufLen-1 || preLen==sufLen+1){
result=true;
k=str.length; //breaks the while loop
}
else
result=false;
}
else
k++;
}
}
return result;
}

Java: BufferedReader lines compared to String issues

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.

Java: Comparing strings

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.

How to search the whole string for a specific word?

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.

Find a char optimization

So this part of the homework wants us to take a Set of Strings and we will return a List of Strings. In the String Set we will have email addresses ie myname#uark.edu. We are to pull the first part of the email address; the name and put it in the String List.From the above example myname would be put into the List.
The code I currently have uses an iterator to pull a string from the Set. I then use the String.contains("#") as an error check to make sure the String has an # symbol in it. I then start at the end of the string and use the string.charAt("#") to check each char. Once It's found i then make a substring with the correct part and send it to the List.
My problem is i wanted to use something recursive and cut down on operations. I was thinking of something that would divide the string.length()/2 and then use String.contains("#") on the second half first. If that half does contain the # symbol then it would call the functions recursively agin. If the back half did not contain the # symbol then the front half would have it and we would call the function recursively sending it.
So my problem is when I call the function recursively and send it the "substring" once I find the # symbol I will only have the index of the substring and not the index of the original string. Any ideas on how to keep track of it or maybe a command/method I should be looking at. Below is my original code. Any advice welcome.
public static List<String> parseEmail(Set<String> emails)
{
List<String> _names = new LinkedList<String>();
Iterator<String> eMailIt=emails.iterator();
while(eMailIt.hasNext())
{
String address=new String(eMailIt.next());
boolean check=true;
if(address.contains("#"))//if else will catch addresses that do not contain '#' .
{
String _address="";
for(int i=address.length(); i>0 && check; i--)
{
if('#'==address.charAt(i-1))
{
_address=new String(address.substring(0,i-1));
check=false;
}
}
_names.add(_address);
//System.out.println(_address);//fill in with correct sub string
}
else
{
//System.out.println("Invalid address");
_names.add("Invalid address");//This is whats shownn when you have an address that does not have an # in it.
} // could have it insert some other char i.e. *%# s.t. if you use the returned list it can skip over invalid emails
}
return _names;
}
**It was suggested I use the String.indexOf("#") BUT according to the API this method only gives back the first occurrence of the symbol and I have to work on the assumption that there could be multiple "#" in the address and I have to use the last one. Thank you for the suggestion though. Am looking at the other suggestion and will report back.
***So there is a string.lastindexOf() and that was what I needed.
public static List<String> parseEmail(Set<String> emails)
{
List<String> _names = new LinkedList<String>();
Iterator<String> eMailIt=emails.iterator();
while(eMailIt.hasNext())
{
String address=new String(eMailIt.next());
if(address.contains("#"))//if else will catch addresses that do not contain '#' .
{
int endex=address.lastIndexOf('#');
_names.add(address.substring(0,endex-1));
// System.out.println(address.substring(0,endex));
}
else
{
// System.out.println("Invalid address");
_names.add("Invalid address");//This is whats shownn when you have an address that does not have an # in it.
} // could have it insert some other char i.e. *%# s.t. if you use the returned list it can skip over invalid emails
}
return _names;
}
Don't reinvent the wheel (unless you were asked too of course). Java already has a built-in function for what you are attempting String.indexOf(String str). Use it.
final String email = "someone#example.com";
final int atIndex = email.lastIndexOf("#");
if(atIndex != -1) {
final String name = email.substring(0, atIndex);
}
I agree to the previous two answers, if you are allowed to use the built-in functions split or indexOf then you should. However if it is part of your homework to find the substrings yourself you should definitely just go through the string's characters and stop when you found the # aka linear search.
You should definitely not under no circumstances try to do this recursively: The idea of divide and conquer should not be abused in a situation where there is nothing to gain: Recursion means function-call overhead and doing this recursively would only have a chance of being faster than a simple linear search if the sub-strings were searched in-parallel; and even then: the synchronization overhead would kill the speedup for all but the most gigantic strings.
Unless recursion is specified in the homework, you would be best served by looking into String.split. It will split the String into a String array (if you specify it to be around '#'), and you can access both halves of the e-mail address.

Categories