I need to get the name of an image path, which is a String. How could i say programmatically in dart "when you find the first / from the right hand side split it, then give it to me"?
the string which i need to split is:
'/data/data/com.example.trail/cache/IMG_1645484057312.png'
CodePudding user response:
You can use split
like the @scott-deagan answer for it. But if you intend to support cross-platform path manipulation, you need to use path package.
Example:
import 'package:path/path.dart' as p;
void main() {
var filepath = '/data/data/com.example.trail/cache/IMG_1645484057312.png';
print(p.basename(filepath));
print(p.basenameWithoutExtension(filepath));
}
result:
IMG_1645484057312.png
IMG_1645484057312
CodePudding user response:
void main() {
var someFile = '/data/data/com.example.trail/cache/IMG_1645484057312.png';
var fname = (someFile.split('/').last);
var path = someFile.replaceAll("/$fname", '');
print(fname);
print(path);
}
CodePudding user response:
Here is the way I recommend you to test
First, do the split on the original string by "/" splitter, then extract the last member of the list created by the splitter to get the name of the png file.
Second, for extracting the remaining string (i.e. the file path), use the substring method of the class string. just by subtracting the original string length from the last_member length in the previous portion, you are able to get the file path string.
Hope to be useful Bests
void main() {
String a = '/data/data/com.example.trail/cache/IMG_1645484057312.png';
var splited_a = a.split('/');
var last_image_index = splited_a.last;
String remaining_string = a.substring(0, a.length - last_image_index.length);
print(remaining_string);
print(last_image_index);
}
result:
the result of path and file extraction from a string in dart