TareqElgafy TareqElgafy - 3 months ago 9
Java Question

get all occurence of substring between two chracters in java

I have String Path like this

"/Math/Math1/Algerbra/node"


how I can get all the occurence of substring between "/" and "/" to get (Math-Math1-Algerbra)

Thanks in advance

Answer

I suppose you need the first 3 directories from a path. You can split on delimiter "/" and build from the result the new string. Obvious you have to pay attention if there aren't enough directories in the path.

    String s = "/Math/Math1/Algerbra/node";
    String aux[] = s.split("/");

    System.out.println(aux[1]+"-"+aux[2]+"-"+aux[3]);

Just found something better to join the strings (java 1.8):

    String.join("-", aux[1], aux[2], aux[3]);