Attaullah
Attaullah

Reputation: 4021

How to extract a subString from android java String?

I tried to extract Sub-String from java string, but failed. i tried like this

String text = "audios/{any_number} any_audio_name.mp3";
text= text.substring(text.indexOf('/'), text.indexOf('3')-2);

Updated

I need String contains only any_audio_name and removing audios/ , any number e.g. {123} and .mp3

For example audios/{211} new school poem.mp3 to new school poem

Upvotes: 0

Views: 198

Answers (4)

Attaullah
Attaullah

Reputation: 4021

Thanks for everyone, who give me idea for solving this issue.

 String text = "audios/{any_number}any_audio_name.mp3";
 text= text.substring(text.indexOf('/')+1, text.indexOf('.')).replaceAll("\\{|\\}|[\\d.]","");
 System.out.println(text);

Upvotes: 0

Malinda
Malinda

Reputation: 584

For Your Edited Question.Following Code segment will help you but here i assume that there will be no number within "any_audio_name"

String text = "audios/{any_number}any_audio_name.mp3";
text= text.substring(text.indexOf('/')+1, text.indexOf('.')).replaceAll("[\\d.]", "");;

Upvotes: 1

Qingfei Yuan
Qingfei Yuan

Reputation: 1212

Use regex seems fit here.

public class MyMain{
    public static void main(String args[]) {
        String line = "audios/any_audio_name.mp3";
        String pattern = "audios\\/(.*)\\.mp3";

        // Create a Pattern object
        Pattern r = Pattern.compile(pattern);

        // Now create matcher object.
        Matcher m = r.matcher(line);

        if (m.find()) {
            System.out.println("Found value: " + m.group(1));
        } else {
            System.out.println("NO MATCH");
        }
    }
}

Upvotes: 1

Malinda
Malinda

Reputation: 584

This answer might helpful

String text = "audios/any_audio_name.mp3";
text= text.substring(text.indexOf('/')+1, text.indexOf('.'));

Upvotes: 1

Related Questions