-2

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

2 Answers2

2

You can use "a/b".split("/") to receive an array containing "a" and "b".

You have to pay some attention, as your first character is a separator, too. Also: do not assume that you know the size of the returned array; too often, people get something wrong and run into ArrayIndexOutOfBounds exceptions because they dont't bother to check result.length before accessing the array elements.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
2

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]);
Liviu Stirb
  • 5,876
  • 3
  • 35
  • 40