Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to search String array for substring

Say I have an array of Strings like so:

0 ["Some plain text"]
1 ["Foobar chicken"]

I want to search each String (in each index of the array) for a particular substring, say plain, and then return true when the first instance of the substring is found.

What's the most effecient way to do this?

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. I also hear that using a while and do-while isn't good either.

My Implementation

Here's my simple implimentation using break:

for (String[] index : tmpList) {
    retVal = index[2].toLowerCase().contains(keyword);

    if (retVal) // Break when retVal is true
        break;
}

Where:

  • tmpList is an ArrayList<String[]>
  • keyword is what I'm trying to find
like image 804
FilmiHero Avatar asked Jan 29 '26 19:01

FilmiHero


1 Answers

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

like image 67
tckmn Avatar answered Feb 01 '26 19:02

tckmn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!