i want to split a word into characters. "Amir Abbas" it contains one space. i use:
List<String> singleWord = string.trim().split("");
but final result is:
A, m, i, r, " ", "", A, b, b, a, s
what is "" character? how to exclude it?
I use it in flutter and ios emulator.
The following code does not give your result. It is not splitting an empty character for me. Try typing your string again, eventually you might have a hidden illegal character?
void main() {
List<String> singleWord = "Amir Abbas".trim().split("");
singleWord.forEach((element){
print(element);
});
}
You can filter the list with the where method and exclude the empty spaces
void main() {
List<String> a = ["a", "b", ""];
List<String> b = a.where((e) => e != "").toList();
print(a); // ["a", "b", ""]
print(b); // ["a", "b"]
}
It is working perfectly for me in dart pad and in my application.Run the application again and can u submit the output again
Try this approach by replacing trim() and just using split(). You can alter the below code according to your need
var names = "Amir and Abbas";
List<String> namesSplit = names.split(" ");
for(var i=0;i<namesSplit.length;i++){
for(var j=0; j<namesSplit[i].length;j++){
print(namesSplit[i][j]);
}
}
Output:
A
m
i
r
a
n
d
A
b
b
a
s
You can filter the runes and get all the letters from A-z.
List<String> singleWord = runes.where((rune) => rune > 64 && rune < 123).map((rune) => String.fromCharCode(rune)).toList()
print(singleWord); // prints [A, m, i, r, A, b, b, a, s]
Related
Suppose I have these maps:
Map<int,List<String>> firstMap = {1:["a", "b"]};
Map<int,List<String>> secondMap = {2:["c"]};
Map<int,List<String>> thirdMap = {1:["d"]};
I want to merge them without overwriting values with same key to have this output:
{1: [a, b, d], 2: [c]
I used both spread operator and adAll method and both overwrite the value for key 1 to have {1: [d], 2: [c]}
instead of {1: [a, b, d], 2: [c].
void main() {
Map<int, List<String>> firstMap = {1: ["a", "b"]};
Map<int, List<String>> secondMap = {2: ["c"]};
Map<int, List<String>> thirdMap = {1: ["d"]};
var mergedMap = <int, List<String>>{};
for (var map in [firstMap, secondMap, thirdMap]) {
for (var entry in map.entries) {
// Add an empty `List` to `mergedMap` if the key doesn't already exist
// and then merge the `List`s.
(mergedMap[entry.key] ??= []).addAll(entry.value);
}
}
print(mergedMap); // Prints: {1: [a, b, d], 2: [c]}
}
I have a list that's formatted like {0:"a", 1:"b", 2:"c", 3: "a"} and want to remove dublicate values so that I end up with {0:"a", 1:"b", 2:"c"}. I'm also fine with geting {1:"b", 2:"c", 3: "a"}. What's the most idiomatic way to do this filtering?
package:quiver provides a bidirectional map (BiMap) that makes it an error to add elements that don't have unique values.
Alternatively, one easy way to filter duplicate values is to create a separate Set of values and use it to rebuild the Map:
Map<K, V> removeDuplicateValues<K, V>(Map<K, V> map) {
var valuesSoFar = <V>{};
return {
for (var mapEntry in map.entries)
if (valuesSoFar.add(mapEntry.value)) mapEntry.key: mapEntry.value,
};
}
void main() {
var map = {0: "a", 1: "b", 2: "c", 3: "a"};
print(removeDuplicateValues(map)); // Prints: {0: a, 1: b, 2: c}
}
If you want to change an existing map, you can do the following. I have made it as a extension method but you can of course also just have it as a separate method or some lines of codes:
extension RemoveDuplicateValuesExtension<K, V> on Map<K, V> {
void removeDuplicateValues() {
final valuesSoFar = <V>{};
this.removeWhere((_, value) => !valuesSoFar.add(value));
}
}
void main() {
final map = {0: "a", 1: "b", 2: "c", 3: "a"}..removeDuplicateValues();
print(map); // Prints: {0: a, 1: b, 2: c}
}
As in Dart you can combine several list items into one according to the following condition:
Given List<String> arr = ['2','3','b','*','4','5','6','-','3','4'];
Get arr = ['23','b','*','456','-','34'];
The list is unknown in advance. It can be of any length and with any sequence of characters. And need to combine only the lines that have numbers in them.
I would be grateful for any suggestions.
You are not describing what should happen if there are multiple special characters or letters. So I have made my example so it will only combine numbers:
void main() {
final arr = ['2', '3', 'b', '*', '4', '5', '6', '-', '3', '4'];
print(combine(arr)); // [23, b, *, 456, -, 34]
}
List<String> combine(List<String> input) {
final output = <String>[];
final buffer = StringBuffer();
for (final string in input) {
if (int.tryParse(string) == null) {
if (buffer.isNotEmpty) {
output.add(buffer.toString());
buffer.clear();
}
output.add(string);
} else {
buffer.write(string);
}
}
if (buffer.isNotEmpty) {
output.add(buffer.toString());
}
return output;
}
You can use ''.join() here:
arr = [''.join(arr[0:2]), arr[2], arr[3], ''.join(arr[4:7]), arr[7], ''.join(arr[8:10])]
If you only want to have a condition where you only join numerical values then you can add a for loop beforehand.
I have a list1: var list1 = ["a:1", "b:2", "c:3"];
how can I create list2 based on list1 like this: ["a", "b", "c"]
I thought I would have to use split and forEach but I don't know how to combine it
Maybe this works for you, if and only if you always have the same String length
List<String> list1 = ["a:1", "b:2", "c:3"];
List<String> list2 = list1.map((f) => f.substring(0,1)).toList();
Or if you wanted to have ":" as the basis regardless of the String length for each element then you can try the code below
List<String> list1 = ["a:1", "b:2", "c:3"];
List<String> list2 = list1.map((f) => f.split(":")[0]).toList();
Iterate through all items of the list with forEach.
With every item (which is a string), split it using ':' as separator (or, if its always just one character, simply get the first charaxter of the item.
Add the first element of the result of split (or aimply first charaxter of item) to list2.
var list1 = ["a:1", "b:2", "c:3"];
List list2;
list1.asMap().forEach((key, value) {
list2.add(value.replaceAll(':${key + 1}', ''));
});
Here is my code
I have this map:
var temp= {
'A' : 3,
'B' : 1,
'C' : 2
};
How to sort the values of the map (descending). I know, I can use temp.values.toList()..sort().
But I want to sort in context of the keys like this:
var temp= {
'B' : 1,
'C' : 2
'A' : 3,
};
This example uses a custom compare function which makes sort() sort the keys by value. Then the keys and values are inserted into a LinkedHashMap because this kind of map guarantees to preserve the order.
Basically the same as https://stackoverflow.com/a/29629447/217408 but customized to your use case.
import 'dart:collection';
void main() {
var temp= {
'A' : 3,
'B' : 1,
'C' : 2
};
var sortedKeys = temp.keys.toList(growable:false)
..sort((k1, k2) => temp[k1].compareTo(temp[k2]));
LinkedHashMap sortedMap = new LinkedHashMap
.fromIterable(sortedKeys, key: (k) => k, value: (k) => temp[k]);
print(sortedMap);
}
Try it on DartPad
The SplayTreeMap has a named constructor which accepts map and a comparator which is used to sort given map while building new map. Since SplayTreeMap is a descendant of Map you can easily substitute it.
import 'dart:collection';
void main() {
var unsorted = {'A': 3, 'B': 1, 'C': 2};
final sorted = SplayTreeMap.from(
unsorted, (key1, key2) => unsorted[key1].compareTo(unsorted[key2]));
print(sorted);
}
final Map<String, ClassCategory> category;
...
Map<String, ClassCategory> sorted = SplayTreeMap.from(category,
(key1, key2) => category[key1]!.title.compareTo(category[key2]!.title));
for (var item in sorted.entries) {
...
}