How to split a string at the first occurrence of a separator in Java

2 Answers

0 votes
public class Program {
    public static void main(String[] args) {
        String str = "java go c c++ python c#";

        String[] parts = str.split("c", 2);  // Limit to 2 splits

        System.out.println(parts[0]); 
        System.out.println(parts[1]); 
    }
}



/*
run:

java go 
 c++ python c#

*/

 



answered May 23, 2024 by avibootz
0 votes
public class Program {
    public static void main(String[] args) {
        String str = "java go c c++ python c#";
        int pos = str.indexOf("c");
        String part1 = "", part2 = "";
        
        if (pos != -1) {
            part1 = str.substring(0, pos);
            part2 = str.substring(pos);
        }
        
        System.out.println(part1); 
        System.out.println(part2); 
    }
}



/*
run:

java go 
c c++ python c#

*/

 



answered May 23, 2024 by avibootz

Related questions

1 answer 124 views
1 answer 113 views
1 answer 125 views
1 answer 143 views
1 answer 184 views
...