15

I have this string in my Android Application:

/storage/emulated/0/temp.jpg

I need manipulate the string and to split the string for this output:

temp.jpg

I need always take the last element of the string.

How to this output in java?

I would greatly appreciate any help you can give me in working this problem.

Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Antonio Mailtraq
  • 1,397
  • 5
  • 34
  • 82
  • I notice you've accepted one of the string splitting answers as your preferred answer. Do check the duplicate I've suggested, since you should be using `File` for this. – Duncan Jones Sep 24 '14 at 14:32

5 Answers5

38

This is not a string splitting exercise

If you need to get a file name from a file path, use the File class:

File f = new File("/storage/emulated/0/temp.jpg");
System.out.println(f.getName());

Output:

temp.jpg
Community
  • 1
  • 1
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
12

one another possibility:

String lStr = "/storage/emulated/0/temp.jpg";
lStr = lStr.substring(lStr.lastIndexOf("/")+1);
System.out.println(lStr);
nano_nano
  • 12,351
  • 8
  • 55
  • 83
  • This produces the output `/temp.jpg` since substring is inclusive, and this is not the output that OP desires. In lieu of editing this answer, I would recommend accepting the answer that uses `File` instead. – jewbix.cube Feb 23 '21 at 01:10
4

You can do it with string split: How to split a string in Java

String string = "/storage/emulated/0/temp.jpg";
String[] parts = string.split("/");
String file= parts[parts.length-1]; 
Community
  • 1
  • 1
arlistan
  • 731
  • 9
  • 20
3

Try this:

String path= "/storage/emulated/0/temp.jpg";
String[] parts = path.split("/");
String filename;
if(parts.length>0)
    filename= parts[parts.length-1];  
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Jatin
  • 1,650
  • 3
  • 17
  • 32
0
String string = "/storage/emulated/0/temp.jpg";
String[] splitString = null;
splitString = string.split("/");
splitString[splitString.length - 1];//this is where your string will be

Try using the String function split. It splits the string by your input and returns an array of strings. Just access the last element of the array in your case.

brso05
  • 13,142
  • 2
  • 21
  • 40