-2

I have the following function.

static String getFilenameURL(String url) {
    String ret = "";
    for (int i = url.length() - 1; i >= 0; i--) {
      if (url.charAt(i) == '/') {
        for (int j = i + 1; url.length() > j; j++) {
          ret += url.charAt(j);
        }
        break;
      }
    }
    return ret;
  }

It goes backwards looking for a Forward slash then copies the string from the backslash. But in C you could just put a pointer to the part you want to return instead of copying from bottom up to the String end, is there an equivalent in Java for this?

AGEERRTT
  • 7
  • 1
  • 3
    [`String#lastIndexOf`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/String.html#lastIndexOf(int)), [`String#substring`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/String.html#substring(int))? – MadProgrammer Apr 18 '23 at 00:39
  • `url.substring(url.lastIndexOf("/"))` - just beware that you should the result of `lastIndexOf` and make it doesn't return a value `< 0` and this will include the `/` character at the start of resulting string – MadProgrammer Apr 18 '23 at 00:41
  • 1
    No. There are no unconstrained pointers. And strings are immutable. You need to make a new string. (What that does behind the scenes is not defined). – Arfur Narf Apr 18 '23 at 00:46
  • 1
    Delete the `j` loop and change `break;` to `return url.substring(i + 1);` – Bohemian Apr 18 '23 at 00:50
  • @shmosel - indeed, thus my parenthetical. But one should banish such thoughts when programming. All I "know" to be true is what it says in the documented interface. – Arfur Narf Apr 18 '23 at 00:54
  • 1
    @shmosel: I don't believe that's been true [since Java 7](https://stackoverflow.com/a/15612188/869736). – Louis Wasserman Apr 18 '23 at 01:48

1 Answers1

1
public static String getFileName(String url) {
    if (url.contains("/")) {
        return url.substring(url.lastIndexOf("/") + 1);
    }
    return "not a valid url";
}
Teletubbies
  • 43
  • 10
  • Context is everything, I personally, would return the `url` as is if it didn't contain a `/` or throw an exception, but as I said, context is everything ;) – MadProgrammer Apr 18 '23 at 01:04
  • My objective was to save time by starting from the end of the url because that's where the filename being accessed is and just setting a pointer to the first forward slash occurrence so it doesn't need to copy the memory again, as Arfur Narf said, that's impossible in Java. – AGEERRTT Apr 18 '23 at 17:57