I'm a beginner in dart.
void main() {
var abf = '+37.4054-122.0999/';
var abf2;
abf2 = abf.replaceAll("+"," ");
var abf1 = abf2.split(RegExp('(?=[+-])'));
print (abf1[0]);
print (abf1[1]);
}
The above code splits abf into two values for me
I want to remove the ending '/'. I tried many split methods using other variables but it's not removing the '/' even though its removing the '+'.
It's not really clear what you're trying to do with the split.
But if you're looking the remove the / this should work:
String number = '+37.4054-122.0999/';
number = number.replaceAll("/"," ");
You can create substring from this while you like to remove last element.
String abf = '+37.4054-122.0999/';
final result = abf.substring(0, abf.length - 1);
print(result);
Dart's List class has a built-in removeLast method. Maybe you can try to split the string and then removing the last element:
String str = "str";
String newStr = str.split(''). removeLast().join('');
Related
I have a String with different value every time:
String words = "My name is Rob Joe";
I want to get only last word
Joe
but every time I don't know how many words the string consists of
String words = "My name is Rob Joe";
var array = words.split(" "); // <-- [My, name, is, Rob, Joe]
print(array.last); // output 'Joe'
In Flutter(Dart), you can get the last word of a string by splitting the string into an array of substrings using the split method and then accessing the last element of the resulting array. Here's an example:
String words = "My name is Rob Joe";
List<String> wordsArray = myString.split(" ");
String lastWord = wordsArray[wordsArray.length - 1];
print(lastWord); // "Joe"
Instead of splitting, you can also use substring and lastIndexOf:
final words = "My name is Rob Joe";
final lastWord = words.substring(words.lastIndexOf(" ") + 1);
print(lastWord);
If you want to find the last word, you should first properly define what a "word" is.
It's clearly obvious here, which is why it's doubly important to write it down, because something else may be just as obvious to someone else.
(Read: Nothing is obvious. Document it all!)
But let's say that a word is a maximal contiguous sequence of ASCII letters.
Then that's what you should look for.
Splitting on space characters works for this string, but won't if you have punctuation, or trailing whitespace, or any number of other complications.
I'd probably use a RegExp:
// Matches a word. If used properly, only matches entire words.
var wordRE = RegExp(r"[a-zA-Z]+");
// Assume at least one word in `words`. Otherwise need more error handling.
var lastWord = wordRe.allMatches(words).last[0]!;
This can be a little inefficient, if the string is long.
Another approach that might be more efficient, depending on the RegExp implementation, is to search backwards:
/// Captures first sequence of [a-zA-Z]+ looking backwards from end.
var lastWordRE = RegExp(r"$(?<=([a-zA-Z]+)[^a-zA-Z]*)");
var lastWord = lastWordRE.firstMatch(words)?[1]!;
If you don't want to rely on RegExps (which are admittedly not that readable, and their performance is not always predictable), you can search for letters manually:
String? lastWord(String words) {
var cursor = words.length;
while (--cursor >= 0) {
if (_isLetter(words, cursor)) {
var start = 0;
var end = cursor + 1;
while (--cursor >= 0) {
if (!_isLetter(words, prev)) {
start = cursor + 1;
break;
}
}
return words.substring(start, end);
}
}
return null;
}
bool _isLetter(String string, int index) {
var char = string.codeUnitAt(index) | 0x20; // lower-case if letter.
return char >= 0x61 /*a*/ && char <= 0x7a /*z*/;
}
But first of all, decide what a word is.
Some very real words in common sentences might contain, e.g., ' or -, but whether they matter to you or not depends on your use-case.
More exotic cases may need you to decide whether"e.g." is one word or two? Is and/or? Is i18n?
Depends on what it'll be used for.
How can i outputs result between 2 specific characters in dart String
example
String myVlue = 'helloWorld';
wanted result is : anything between 'hel' and 'ld'
so the result is 'loWor'
Note : in my case the two specific characters are fixed and Unique
How can i tell dart to do that in best way .
thanks
You could define a regular expression to catch a group from your input:
void main() {
String myValue = 'helloWorld';
RegExp regExp = RegExp(r'hel(.*)ld');
String extract = regExp.firstMatch(myValue)![1]!;
print(extract); // loWor
}
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'
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
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);
}
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
How do I get the last n-characters in a string?
I've tried using:
var string = 'Dart is fun';
var newString = string.substring(-5);
But that does not seem to be correct
var newString = string.substring(string.length - 5);
Create an extension:
extension E on String {
String lastChars(int n) => substring(length - n);
}
Usage:
var source = 'Hello World';
var output = source.lastChars(5); // 'World'
While #Alexandre Ardhuin is correct, it is important to note that if the string has fewer than n characters, an exception will be raised:
Uncaught Error: RangeError: Value not in range: -5
It would behoove you to check the length before running it that way
String newString(String oldString, int n) {
if (oldString.length >= n) {
return oldString.substring(oldString.length - n)
} else {
// return whatever you want
}
}
While you're at it, you might also consider ensuring that the given string is not null.
oldString ??= '';
If you like one-liners, another options would be:
String newString = oldString.padLeft(n).substring(max(oldString.length - n, 0)).trim()
If you expect it to always return a string with length of n, you could pad it with whatever default value you want (.padLeft(n, '0')), or just leave off the trim().
At least, as of Dart SDK 2.8.1, that is the case. I know they are working on improving null safety and this might change in the future.
var newString = string.substring((string.length - 5).clamp(0, string.length));
note: I am using clamp in order to avoid Value Range Error. By that you are also immune to negative n-characters if that is somehow calculated.
In fact I wonder that dart does not have such clamp implemented within the substring method.
If you want to be null aware, just use:
var newString = string?.substring((string.length - 5).clamp(0, string.length));
I wrote my own solution to get any no of last n digits from a string of unknown length, for example the 5th to the last digit from an n digit string,
String bin='408 408 408 408 408 1888';// this is the your string
// this function is to remove space from the string and then reverse the
string, then convert it to a list
List reversed=bin.replaceAll(" ","").split('').reversed.toList();
//and then get the 0 to 4th digit meaning if you want to get say 6th to last digit, just pass 0,6 here and so on. This second reverse function, return the string to its initial arrangement
var list = reversed.sublist(0,4).reversed.toList();
var concatenate = StringBuffer();
// this function is to convert the list back to string
list.forEach((item){
concatenate.write(item);
});
print(concatenate);// concatenate is the string you need
I want a simple function that can remove part of a string, eg:
var foo="oranges";
trace(removeStrings(foo,'rang'));
I want the above output as 'oes'. Any help will be greatly appreciated.
Thanks in advance
A quick solution for removing substrings is to use split with the string that you want to remove as delimiter and then join the result:
function removeSubString(str, remove):String {
return str.split(remove).join("");
}
Another way to do this is
function removeStrings(originalString, pattern):String
{
return originalString.replace(pattern, "");
}
For more information about Strings in AS3 you can visit:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html
I should mention that the code above is not going to change your String, so if you need to use the property originalString with the new value you should use:
originalString = removeStrings(originalString, pattern);
The second thing that I should mention is that the replace method will replace the first appearance of the pattern, so if you need to replace every match of the pattern you should do something like
while(originalString.search(pattern) != -1)
{
originalString = removeStrings(originalString, pattern);
}
Hope this will help!
Ivan Marinov
I'm using by long time this snippet, which as the advantage to be available to all string objects on your movie:
String.prototype.replace = function(pattern, replacement) {
return this.split(pattern).join(replacement);
}
can be used in this way:
var str = "hello world";
var newstr = str.replace("world", "abc");
trace(newstr);
as you can see the string class have been extended with the replace method.