How to write an equivalent to PHP explode(string $separator, string $string, int $limit = INT_MAX): array in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

public class ExplodeExample {

    public static List<String> explode(String separator, String input, int limit) {
        List<String> result = new ArrayList<>();
        int start = 0;
        int splits = 0;
        int sepLen = separator.length();

        while (true) {
            int end = input.indexOf(separator, start);
            if (end == -1 || splits >= limit - 1) {
                break;
            }
            result.add(input.substring(start, end));
            start = end + sepLen;
            splits++;
        }

        // Add the remaining part
        result.add(input.substring(start));
        
        return result;
    }

    public static void main(String[] args) {
        String text = "c++,c,python,php,java";
        String delimiter = ",";
        int limit = 3;

        List<String> parts = explode(delimiter, text, limit);

        for (String part : parts) {
            System.out.println(part);
        }
    }
}



/*
run:

c++
c
python,php,java

*/

 



answered Nov 20, 2025 by avibootz

Related questions

...