bad mom
bad mom

Reputation: 59

How to extract particular part of a string?

I have a Link which never changes. The only thing which changes is the file name (in bold). so how do I get the file name from this link? I want to display this in a textview or toast-

http://apkins.aptoide.com/aptoide-8.1.0.1.apk?=x

Upvotes: 1

Views: 189

Answers (3)

creativecreatorormaybenot
creativecreatorormaybenot

Reputation: 126624

String given = "http://apkins.aptoide.com/aptoide-8.1.0.1.apk?=x";
String extractedAppName = given.substring(given.lastIndexOf("/") + 1, given.lastIndexOf("?"));

This should work. It takes the position of the / before the name and then the position of the ?. It takes the string (substring) between those two characters. Just give it a try and you'll see.

Upvotes: 1

slyidiot
slyidiot

Reputation: 78

This should do the trick

String fileName = url.substring(url.lastIndexOf('/') + 1);

You can also try URLUtil.guessFileName(url, null, null)

Edit 1

String url = "any url"

Upvotes: 1

Sweeper
Sweeper

Reputation: 270840

Here is a regex-less solution:

public static String getFileName(String link) {
     int endIndex = link.lastIndexOf('?');
     return link.substring(26, endIndex);
 }

It's pretty simple. It first gets where the file name ends i.e. the position of the last "?". Then it "cuts out" a new string from the link starting from the 27th character to the end of the file name.

Upvotes: 1

Related Questions