-4

I have:

/xxx/yyy/aaa/bbb/abc.xml (or)
/xxx/yyy/aaa/abc.xml (or)
/xxx/yyy/aaa/bbb/ccc/abc.xml

But I need only:

/xxx/yyyy

How do I implement this in Java? Thanks in advance.

  • 5
    thanks in advance won't work; show us what you have tried and what failed. SO is not a code writing service. – epoch Jun 07 '17 at 11:02
  • 1
    Welcome to Stackoverflow ! Please visit [help] – akash Jun 07 '17 at 11:02
  • See [`String.substring`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#substring(int)) and [`String.indexOf`](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#indexOf(java.lang.String,%20int)). With those twos, you can do it simply, so simply that I will let you do it. – AxelH Jun 07 '17 at 11:04
  • 1
    Try `str.replaceAll("((/[^/]*){2}).*", "$1")`. –  Jun 07 '17 at 11:11
  • Does this answer your question? [How to split a string in Java](https://stackoverflow.com/questions/3481828/how-to-split-a-string-in-java) – pringi Mar 04 '22 at 21:55

3 Answers3

1

You can use StringUtils class for this.

Sample code snippet for your question,

    String str = "/xxx/yyy/aaa/bbb/abc.xml";

    int index = StringUtils.ordinalIndexOf(str , "/" , 3);

    String result = str.substring(0,index);

Or you can use indexOf method iteratively,

    String str = "/xxx/yyy/aaa/bbb/abc.xml";

    int index = 0 , count = 1;

    while(count != 3)
    {
         index = str.indexOf("/" , index+1);
         count++;
    }

    String result = str.substring(0,index);
0

You can use String.split("/") for splitting and concat first 2 elements:

for(String string: input){
  String[] splitedStrings = string.split("/");
  StringBuilder result = new StringBuilder("/");
  for(int i = 1; i < 3 && i < splitedStrings.length; i++){
    result.append(splitedStrings[i]).append("/");
  }
  System.out.println("Result: " + result.toString());
}

https://pastebin.com/kpg5VtMk

0
FilenameUtils.getFullPathNoEndSeparator(str).replaceAll("((/[^/]*){2}).*", "$1")

I used this its working fine for me.