use
while (contains == false)
instead
while (contains = false)
= is an assign operator and == is comparision operator. you are assigning false to contains in while loop. You have to compare the values
use
while (contains == false)
instead
while (contains = false)
= is an assign operator and == is comparision operator. you are assigning false to contains in while loop. You have to compare the values
Avoid while loop. Use break statement. If not careful, while loops can cause infinite loops.
private static void teamSearch(String teamName) {
String subString = teamName;
String string = "";
boolean contains = false;
for (int i = 0; i < clubList.size(); i++){
string = clubList.get(i).aliases;
if (string.contains(subString)) {
contains = true;
break;
}
}
System.out.println(contains);
}
I know I can do a simple break in a for-loop but I've heard people say that using break in a for-loop is bad-practice.
Where did you find this? That is completely wrong. Is it a bad practice to use break in a for loop?
Just use a for loop and loop through the Strings. Use String#contains to check to see if the String has a specific substring. Then store the String in a variable (or the index if you need it) and break;.
I know that apache-commons has a utility class called StringUtils that could give you a elegant solution.
public boolean foo(String[] array, String pattern){
for(String content : array){
if(StringUtils.contains(content, pattern){
return true;
}
}
return false;
}
One thing I don't like about this is that it will only return true at the first found instance. I'm not entirely sure what you are attempting to do but if you don't if don't care about indexes in the array that don't match the pattern, I would recommend using the higher order function called filter.
Guava, lambdaJ, and Apache-Commons, are libraries that have support for functional programming.
Below is some sudo-code that should work in Apache-Commons.
List<String> content = Arrays.asList(strArray);
Predicate matchesPattern = new Predicate("asdf"){{
private String pattern;
public Predicate(String pattern){
this.pattern = pattern;
}
@Overload
public boolean evaluate(Object input){
if(input instanceOf String){
StringUtils.contains((String)input, pattern
}
return false;
}
}};
CollectionUtils.filter(content, matchesPattern);
What this does is remove any String from the list that doesn't matches the pattern. As you can see it's a little verbose declaring a Predicate object. If you use Apache-Commons or Guava it's going to look similar, but that's where lambdaJ comes to the rescue.
A predicate is just term for function that takes in a single argument and returns a boolean value, you probably already used them before with the Matcher class. Hamcrest has some of the best Matcher's library available, so lambdaJ just built a functional programming library around it. It's easy to use and highly readable.
Use Arrays.copyOfRange:
public static <T> T[] copyOfRange(T[] original,
int from,
int to)
Copies the specified range of the specified array into a new array. The initial index of the range (
from) must lie between zero andoriginal.length, inclusive. The value atoriginal[from]is placed into the initial element of the copy (unlessfrom == original.lengthorfrom == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater thanoriginal.length, in which case null is placed in all elements of the copy whose index is greater than or equal tooriginal.length - from. The length of the returned array will beto - from.The resulting array is of exactly the same class as the original array.
In your case:
String[] grp = Arrays.copyOfRange(elements, i, i + n);
You will use Arrays.copyOfRange().
Here is an example:
String[] original = some array;
String[] grp = Arrays.copyOfRange(original, i, i + n);
The Javadocs for the Arrays class has lots of information about the method:
This will solve the issue..
Approach 1:
int retval = aList.indexOf(letter.charAt(0));
Approach 2:
int index = Arrays.binarySearch(anArray, letter.charAt(0));
The problem is that you are having a character Array aList, and the letter is a String and hence it search for a String in the Character array. Which can possibly cause ClassCastException or String not found.
In short :
Character Ais not same asString A
Approach 1:
when running document and inputting a letter, -1 is returned even if the list contains the letter.
ok, this problems @Dileep has already answered,
int retval = aList.IndexOf(letter);
Mistake is that you have passed a String type to List.indexOf(Object o) were, aList
contains all elements of type Character. So List.indexOf() will always return -1.
you may change to work:
int retval = aList.indexOf(Character.toUpperCase(letter.charAt(0)));
Note: Character.toUpperCase() i have used because you have all elements in upper case.
Approach 2:
throws
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Character
exception message has already answered, that String cannot be a changed/cast to Character,
int index = Arrays.binarySearch(anArray, letter);
Here,
anArraycontains elements type ofCharacteryou have passed a
StringtoArrays.binarySearch(), instead of acharorCharacter, internally whenArrays#binarySearch()invokesCharacter.compareTo(T o)here, the specified object's type(i.e.letter#String) prevents it from being compared to Character object. then theClassCastExceptionis throwed.
Solution:
int index = Arrays.binarySearch(anArray, Character.toUpperCase(letter.charAt(0)));
for(int i=0; i<list.size(); i++) {
String s = list.get(i);
int x = s.indexOf('(');
if(x==-1) break;
return s.substring(x+1);
}
Pass the strings you want to check to a method that does something like this:
if(str.contains("(")){
return str.substring(str.indexOf("("));
}else{
return null;
}
Usually I dont do this, but today is Saturday and I am happy and probably going to get drunk
public void find(String line ) {
boolean found = false;
int i = 0;;
while (i < doc.size()) {
if ((doc.get(i).indexOf( line ) > 0)){
cursor = i;
found = true;
break;
}else {
i++;
}
}
if (found) {
// print cursor or do whatever
}
}
You should note if this is homework.
One way to do this is:
int i = 0;
String searchTerm = "ta";
System.out.println("Following substrings contain search term:");
for (String s : "hi guys,this,is,sparta".split(",")) {
if (s.contains(searchTerm)) System.out.println(i++);
else i++;
}
Or if you prefer using regex, then change s.contains(searchTerm) with s.matches(searchTerm).
If this is not homework, but interview question or work problem, this would be vastly more complex. For example: aminoacid sequence is search term and need to find locations in DNA/RNA where it is located. In that case you need more complex solution.
Examples:
- Brute-Force String Matching
- Suffix Trees String Matching Algorithm ( wiki )
- Boyer-Moore String Matching Algorithm ( wiki )
- Knuth-Morris-Pratt String Matching ( wiki )
- Sunday String Matching algorithm ( wiki )
- Horspool String Matching algorithm ( wiki )
- Rabin-Karp string matching algorithm ( wiki )
- Aho–Corasick string matching algorithm ( wiki )
NOTE: IF YOU WANT TO SHOW ALL STRINGS THAT START WITH YOUR INPUT, READ THIS.
As you want all the strings that start with the given input, any string matching algorithm like KMP or Boyer Moore is not going to give you good results. Because you have to iterate over all the string in the array and compare(If you want want suffix, KMP does not do any better than linear search).
A better option would be to construct a Trie with your array and when you want to show the result of autoComplete, just traverse through the array and show all words under your current Node.
for your input array = ["abas", "aras", "as", "ask", "asi", "aso", "atas" ,"best","test"]
The corresponding Trie would be : ('.' represents end of the string)
I did not add test but the structure will be just like best
DUMMY
/ \
a b
/ | \ |
b r s est.
/ | ?
as. as.
The tree in place of ? would look like :
s.
/ | \
k. i. o.
When you want to search all strings that start with as, you have to just traverse in the path as and print all words under it. Here {as,ask,asi,aso}
Boyer Moore - Horspool algorithm is a fast way for string search. It is a good way to finding substrings in mega texts
This is what you're looking for:
List<String> dan = Arrays.asList("Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue");
boolean contains = dan.contains(say.getText());
If you have a list of not repeated values, prefer using a Set<String> which has the same contains method
String[] a= {"tube", "are", "fun"};
Arrays.asList(a).contains("any");
Do something like:
Arrays.asList(array).contains(x);
since that return true if the String x is present in the array (now converted into a list...)
Example:
if(Arrays.asList(myArray).contains(x)){
// is present ... :)
}
since Java8 there is a way using streams to find that:
boolean found = Arrays.stream(myArray).anyMatch(x::equals);
if(found){
// is present ... :)
}
You could also use the commons-lang library from Apache which provides the much appreciated method contains.
import org.apache.commons.lang.ArrayUtils;
public class CommonsLangContainsDemo {
public static void execute(String[] strings, String searchString) {
if (ArrayUtils.contains(strings, searchString)) {
System.out.println("contains.");
} else {
System.out.println("does not contain.");
}
}
public static void main(String[] args) {
execute(new String[] { "AA","BB","CC" }, "BB");
}
}