简体   繁体   中英

How to Write For Each Loop to Process Through String Array to Count Substrings

Was using a for loop to process through a String array and to test if the content of the cell matched with a substring, if so, count++.

The compiler is telling me that this can be written as a for-each loop. I'm not very experienced using for-each loops, and the geeks for geeks articles are not helping.

Could someone kindly walk me through this simple conversion?

for(int i = 0; i < parts.length; i++){
        if(parts[i].contains(subString)){
            count++;
        }
    }

    System.out.print(count);

Assuming that parts is a String array, you can do

for (String p : parts) {
    if(p.contains(subString))
    {
        count++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM