如何在Java中删除字符串的一部分?



如何在Java中删除字符串的一部分?在这种情况下,字符串是一个链接。

当前状态:

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

应该是什么样子

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

我在Stack Overflow上发现了类似的东西,但它仍然显示整个字符串而不是拆分版本。

String categoryURL = link;
categoryURL.substring(0, categoryURL.lastIndexOf("/"));

在Java中字符串是不可变的。这意味着,您不能更改当前字符串,而substring方法将生成一个新字符串。所以你可以把你的新字符串赋值给一个新的变量,或者赋值给同一个变量。例如:

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);

最新更新