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

Answer from stinepike on Stack Overflow
🌐
CodeGym
codegym.cc › java blog › strings in java › substring in java
Java String substring()
String x = "CodeGymIsTheBest"; String y = x.substring (2,6); String z = x.substring (0,3); So, in JDK 7 and later, objects y and z created as a result of the substring() method applied to object x will refer to two newly created arrays (on the ...
Published: July 23, 2024
🌐
Coderanch
coderanch.com › t › 486735 › java › fast-substring-search-Array-strings
How to do a fast substring search on an Array of strings? (Java in General forum at Coderanch)
March 11, 2010 - Next, indexOf() performs only search of the substring. Using the whole matching regular expression is quite unfair since the regular expression with the matches() method should match each string character. Exact equivalent of text.indexOf("needle") would be Pattern.compile("needle").matche...
Top answer
1 of 2
6

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;.

2 of 2
0

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.

🌐
Stack Overflow
stackoverflow.com › questions › 29382983 › getting-a-substring-of-an-array-in-java
Getting a substring of an array in java - Stack Overflow
java.util.Arrays.copyOfRange (specialized for each primitive element type or Object) gives a portion, in the same order, like String.substring. AFAICT there is no direct way to reverse an array. ... Could you not simply identify the number set and location form within the array that you wish to use and then start from the next index and search for the first or last number in your sequence and then once you find it then begin to search for the next number?
🌐
Ranjan
javacodepoint.com › logical-programs › find-strings-containing-a-substring
Find Strings Containing a Substring in an Array - Javacodepoint
January 25, 2025 - In this article, we will learn how to write a Java program to find all strings in an array that contain a given substring.
🌐
Stack Overflow
stackoverflow.com › questions › 56069923 › find-the-substring-of-an-element-in-the-string-array-at-index
java - Find the substring of an element in the String array at index - Stack Overflow
public static void main(String[] args) throws FileNotFoundException { final int TOTALNAMES = 15; int cntr = 0; String [] names = new String[TOTALNAMES]; String [] firstname = new String[TOTALNAMES]; String [] lastname = new String[TOTALNAMES]; File file = new File("Names12.txt"); Scanner read = new Scanner(file); printHeading(); while(read.hasNext() && cntr < TOTALNAMES){ cntr++; names[cntr - 1] = read.nextLine(); } read.close(); for(int i = 0; i < cntr; i++){ //firstname[i] = names[i].substring(0, names[i].indexOf(" ")); lastname[i] = names[i].substring(names[i].indexOf(" ") + 1); System.out.println(lastname[i]); } }
Find elsewhere
Top answer
1 of 2
4

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 A is not same as String A

2 of 2
1

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,

  • anArray contains elements type of Character

  • you have passed a String to Arrays.binarySearch(), instead of a char or Character, internally when Arrays#binarySearch() invokes Character.compareTo(T o) here, the specified object's type(i.e. letter#String) prevents it from being compared to Character object. then the ClassCastException is throwed.

Solution:

int index = Arrays.binarySearch(anArray, Character.toUpperCase(letter.charAt(0)));
🌐
Coderanch
coderanch.com › t › 695164 › java › String-search-substring-based-array
String - search for substring based on array (Beginning Java forum at Coderanch)
June 10, 2018 - A solution has already been mentioned: Stream... filter... findFirst, eventually followed by orElse if you don't want to return an optional · There are three kinds of actuaries: those who can count, and those who can't. ... Boost this thread! ... Sorting elements in an array based off user input responses.
🌐
CodeSignal
codesignal.com › learn › courses › practicing-string-operations-and-type-conversions-in-java › lessons › string-manipulation-finding-all-substring-occurrences-in-java
String Manipulation: Finding All Substring Occurrences in ...
The next step is to find the subsequent instances of the substring in the original. To do this, we will use a while loop. But when should we stop looking for more occurrences? When our indexOf function returns -1, it indicates there are no more matches to be found.
🌐
HappyCoders
happycoders.eu › home › java › java substring() method
Java substring() Method
June 12, 2025 - In Java 9, the substring method has been modified to take into account the encoding used (1-byte Latin 1 vs. 2-byte UTF-16). However, the basic functionality (calling Arrays.copyOfRange) has been retained. I wrote a small program to demonstrate the changes of the substring method over the Java versions. You can find ...
🌐
TutorialsPoint
tutorialspoint.com › extracting-a-substring-as-an-array-of-characters-in-java
Java - String getChars() Method
The getChars() method accepts four different parameters that hold the value of the source begin index, source end index, destination char array, and destination begin index. It throws an exception if the srcBegin value is negative, srcBegin ...
🌐
W3Schools
w3schools.com › java › ref_string_substring.asp
Java String substring() Method
Java Wrapper Classes Java Generics ... Lambda Java Advanced Sorting ... How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Num Random Number Count Words Count Vowels in a String Remove Vowels Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average ...