-1

How is it possible to cut out a part of a string in Java? In that case the string is a link.

current state:

https://stackoverflow.com/questions/68779331/use-token-to-push-some-codes-to-github

What it should look like

https://stackoverflow.com/questions/68779331/

I found something like this on Stack Overflow, but it still shows the whole string instead of the split version.

String categoryURL = link;
categoryURL.substring(0, categoryURL.lastIndexOf("/"));
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
knödel
  • 124
  • 2
  • 11
  • Can you define "not working?" What is your criteria for removing parts of the path? (Those are two separate questions.) – markspace Aug 25 '21 at 17:22
  • "*I found something like this on stackoverflow but it is not working.*" - What does "*not working*" mean? Does it not compile? If so: please [edit] the post and add the compilation error. Does it throw an exception? If so: please [edit] the post and add the stack trace. Does it show unexpected behaviour? If so: please [edit] the post, add a [MRE] and describe desired and observed behaviour. --- From the [docmentation of `String`](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lang/String.html): "*... String objects are immutable...*" – Turing85 Aug 25 '21 at 17:23

1 Answers1

3

In Java Strings are immutable. This means, you cannot change your current string, and the substring method will generate a new string. So you can assign your new string to a new variable, or to the same variable. For example:

String categoryURL = "https://stackoverflow.com/questions/68779331/use-token-to-push-some-codes-to-github";
    categoryURL = categoryURL.substring(0, categoryURL.lastIndexOf("/"));
    System.out.println(categoryURL);