-3

I have a String like this:

https://www.thetimes.co.uk/article/record-level-of-poorer-teens-aiming-for-a-degree-m6q6bfbq3

And I know that I want to remove this part:

https://www.thetimes.co.uk/article/
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • Does this answer your question? [replace String with another in java](https://stackoverflow.com/questions/5216272/replace-string-with-another-in-java) – Ricky Sixx Jul 14 '22 at 06:08
  • 1
    Please show the expected result. I get the impression that some of the answers misunderstood the goal. Also please show what you tried yourself and explain how it failed. – Yunnosch Jul 14 '22 at 06:18
  • Does this answer your question? [How to replace part of a String in Java?](https://stackoverflow.com/questions/28345198/how-to-replace-part-of-a-string-in-java) – Stephen Taylor Jul 16 '22 at 08:53

4 Answers4

2

Use String::replace

String oldString = "https://www.thetimes.co.uk/article/record-level-of-poorer-teens-aiming-for-a-degree-m6q6bfbq3";

String newString = oldString.replace ("https://www.thetimes.co.uk/article/", "");
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
2

If we phrase the requirement as "remove everything after the last '/'", you can use lastIndexof to find its position and then substring to cut it:

String result = myString.substring(0, myString.lastIndexOf('/') + 1);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

Another solution using a regexp. It could be useful if you need to deal with the case where the input string doesn't start with the known string.

private static final Pattern RE = Pattern.compile("https://www.thetimes.co.uk/article/(.*)");

...

Matcher matcher = RE.matcher(inputString);
if (matcher.matches()) {
    return matcher.group(1);
} else {
    return inputString; // or null, or whatever
}
Maurice Perry
  • 9,261
  • 2
  • 12
  • 24
-1

We can also use substring

String url=https://www.thetimes.co.uk/article/record-level-of-poorer-teens-aiming-for-a-degree-m6q6bfbq3; url.substring(36,url.length);

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 15 '22 at 07:17