how separate string into key/value pair in dart? - string

how can a string be separated into key/value pair in dart? The string is separated by a "=". And how can the pair value be extracted?
main(){
var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];
Map<String ,dynamic> map = {};
for (String s in stringTobeSeparated) {
var keyValue = s.split("=");
//failed to add to a map , to many positiona arguments error
map.addAll(keyValue[0],keyValue[1]);
}
}

The split() function gives you a List of Strings, so you just need to check if the length of this List is equal to 2 and then you can add those values in a Map like this:
Map<String, String> map = {};
for (String s in stringTobeSeparated) {
var list = s.split("=");
if(list.length == 2) {
// list[0] is your key and list[1] is your value
map[list[0]] = list[1];
}
}

You can use map for this, the accepted answer is correct, but since your string looks like this
var stringTobeSeparated = ['ab = cd','ef = gh','ld = kg'];
I would rather use regex to remove spaces from final result (replace the line with split with this):
var list = s.split(RegExp(r"\s+=\s+"));

Related

How to check if a list exist inside another list

So I have a list a that contain the string "ab" and another list b that contain a list that contain the string "ab". So it look something like this:
var a = ["ab"]
var b = [["ab"]]
How can I check if a is in b. I have try using b.includes(a) that result in a false and I also have try b.indexOf(a) which also return false. The way that I currently use is this:
var flag = false
var a = ["ab"]
var b = [["ab"]]
b.forEach((i) => {
if (i.join("") == a.join("")) flag = true
})
console.log(flag)
Is there like a shorter way?
Thanks y'all.
Little trick for you. You can compare two array if you use toString() method.
const a = ["ab"];
const b = [["ab"]];
const result = b.some(p => p.toString().includes(a));
console.log(result);
Not quiet sure what exactly you want to check but here are 2 examples:
var a = ["ab"];
var b = [["ab"]];
var flag = false;
//Example 1: search for "ab" in the nested array
b.forEach(el=>{
el.forEach(innerEl=>{
if(innerEl === "ab") flag = true;
});
});
console.log(`Result 1 ${flag}`);
//Example 1: seach for the exact array ["ab"]
b.forEach(el=>{
if(el == a)flag = true;
});
console.log(`Result 2 ${flag}`);
If you have references you can do as follows:
var a = ["ab"];
var b = [a];
b.includes(a); // true
Otherwise you need to convert those arrays to strings and compare those as others suggested or compare inside values of those nested arrays one by one because:
['a'] != ['a'] // this is true because those are 2 different arrays

How to concatenate two string in Dart?

I am new to Dart programming language and anyone help me find the best string concatenation methods available in Dart.
I only found the plus (+) operator to concatenate strings like other programming languages.
There are 3 ways to concatenate strings
String a = 'a';
String b = 'b';
var c1 = a + b; // + operator
var c2 = '$a$b'; // string interpolation
var c3 = 'a' 'b'; // string literals separated only by whitespace are concatenated automatically
var c4 = 'abcdefgh abcdefgh abcdefgh abcdefgh'
'abcdefgh abcdefgh abcdefgh abcdefgh';
Usually string interpolation is preferred over the + operator.
There is also StringBuffer for more complex and performant string building.
If you need looping for concatenation, I have this :
var list = ['satu','dua','tiga'];
var kontan = StringBuffer();
list.forEach((item){
kontan.writeln(item);
});
konten = kontan.toString();
Suppose you have a Person class like.
class Person {
String name;
int age;
Person({String name, int age}) {
this.name = name;
this.age = age;
}
}
And you want to print the description of person.
var person = Person(name: 'Yogendra', age: 29);
Here you can concatenate string like this
var personInfoString = '${person.name} is ${person.age} years old.';
print(personInfoString);
Easiest way
String get fullname {
var list = [firstName, lastName];
list.removeWhere((v) => v == null);
return list.join(" ");
}
The answer by Günter covers the majority of the cases of how you would concatenate two strings in Dart.
If you have an Iterable of Strings it will be easier to use writeAll as this gives you the option to specify an optional separator
final list = <String>['first','second','third'];
final sb = StringBuffer();
sb.writeAll(list, ', ');
print(sb.toString());
This will return
'first, second, third'
Let's think we have two strings
String a = 'Hello';
String b = 'World';
String output;
Now we want to concat this two strings
output = a + b;
print(output);
Hello World

How to collect a string to a stack of characters in Java 8? [duplicate]

I would like to convert the string containing abc to a list of characters and a hashset of characters. How can I do that in Java ?
List<Character> charList = new ArrayList<Character>("abc".toCharArray());
In Java8 you can use streams I suppose.
List of Character objects:
List<Character> chars = str.chars()
.mapToObj(e->(char)e).collect(Collectors.toList());
And set could be obtained in a similar way:
Set<Character> charsSet = str.chars()
.mapToObj(e->(char)e).collect(Collectors.toSet());
You will have to either use a loop, or create a collection wrapper like Arrays.asList which works on primitive char arrays (or directly on strings).
List<Character> list = new ArrayList<Character>();
Set<Character> unique = new HashSet<Character>();
for(char c : "abc".toCharArray()) {
list.add(c);
unique.add(c);
}
Here is an Arrays.asList like wrapper for strings:
public List<Character> asList(final String string) {
return new AbstractList<Character>() {
public int size() { return string.length(); }
public Character get(int index) { return string.charAt(index); }
};
}
This one is an immutable list, though. If you want a mutable list, use this with a char[]:
public List<Character> asList(final char[] string) {
return new AbstractList<Character>() {
public int size() { return string.length; }
public Character get(int index) { return string[index]; }
public Character set(int index, Character newVal) {
char old = string[index];
string[index] = newVal;
return old;
}
};
}
Analogous to this you can implement this for the other primitive types.
Note that using this normally is not recommended, since for every access you
would do a boxing and unboxing operation.
The Guava library contains similar List wrapper methods for several primitive array classes, like Chars.asList, and a wrapper for String in Lists.charactersOf(String).
The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:
List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);
Use a Java 8 Stream.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Breakdown:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
(I have absolutely no idea why String#chars() returns an IntStream.)
The most straightforward way is to use a for loop to add elements to a new List:
String abc = "abc";
List<Character> charList = new ArrayList<Character>();
for (char c : abc.toCharArray()) {
charList.add(c);
}
Similarly, for a Set:
String abc = "abc";
Set<Character> charSet = new HashSet<Character>();
for (char c : abc.toCharArray()) {
charSet.add(c);
}
List<String> result = Arrays.asList("abc".split(""));
Create an empty list of Character and then make a loop to get every character from the array and put them in the list one by one.
List<Character> characterList = new ArrayList<Character>();
char arrayChar[] = abc.toCharArray();
for (char aChar : arrayChar)
{
characterList.add(aChar); // autoboxing
}
You can do this without boxing if you use Eclipse Collections:
CharAdapter abc = Strings.asChars("abc");
CharList list = abc.toList();
CharSet set = abc.toSet();
CharBag bag = abc.toBag();
Because CharAdapter is an ImmutableCharList, calling collect on it will return an ImmutableList.
ImmutableList<Character> immutableList = abc.collect(Character::valueOf);
If you want to return a boxed List, Set or Bag of Character, the following will work:
LazyIterable<Character> lazyIterable = abc.asLazy().collect(Character::valueOf);
List<Character> list = lazyIterable.toList();
Set<Character> set = lazyIterable.toSet();
Bag<Character> set = lazyIterable.toBag();
Note: I am a committer for Eclipse Collections.
IntStream can be used to access each character and add them to the list.
String str = "abc";
List<Character> charList = new ArrayList<>();
IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));
Using Java 8 - Stream Funtion:
Converting A String into Character List:
ArrayList<Character> characterList = givenStringVariable
.chars()
.mapToObj(c-> (char)c)
.collect(collectors.toList());
Converting A Character List into String:
String givenStringVariable = characterList
.stream()
.map(String::valueOf)
.collect(Collectors.joining())
To get a list of Characters / Strings -
List<String> stringsOfCharacters = string.chars().
mapToObj(i -> (char)i).
map(c -> c.toString()).
collect(Collectors.toList());

Swift - Finding a substring between two locations in a string

I have a string that is formatted like this: "XbfdASF;FBACasc|Piida;bfedsSA|XbbnSF;vsdfAs|"
Basiclly its an ID;ID| and then it repeats.
I have the first ID and I need to find it's partner Example: I have 'Piida' and I need to find the String that follows it after the ';' which is 'bfedsSA'
How do I do this?
The problem I am having is that the length of the IDs is dynamic so I need to get the index of '|' after the ID I have which is 'Piida' and then get the string that is between these indexes which in this case should be 'bfedsSA'.
There are many ways to do this, but the easiest is to split the string into an array using a separator.
If you know JavaScript, it's the equivalent of the .split() string method; Swift does have this functionality, but as you see there, it can get a little messy. You can extend String like this to make it a bit simpler. For completeness, I'll include it here:
import Foundation
extension String {
public func split(separator: String) -> [String] {
if separator.isEmpty {
return map(self) { String($0) }
}
if var pre = self.rangeOfString(separator) {
var parts = [self.substringToIndex(pre.startIndex)]
while let rng = self.rangeOfString(separator, range: pre.endIndex..<endIndex) {
parts.append(self.substringWithRange(pre.endIndex..<rng.startIndex))
pre = rng
}
parts.append(self.substringWithRange(pre.endIndex..<endIndex))
return parts
} else {
return [self]
}
}
}
Now, you can call .split() on strings like this:
"test".split("e") // ["t", "st"]
So, what you should do first is split up your ID string into segments by your separator, which will be |, because that's how your IDs are separated:
let ids: [String] = "XbfdASF;FBACasc|Piida;bfedsSA|XbbnSF;vsdfAs|".split("|")
Now, you have a String array of your IDs that would look like this:
["XbfdASF;FBACasc", "Piida;bfedsSA", "XbbnSF;vsdfAs"]
Your IDs are in the format ID;VALUE, so you can split them again like this:
let pair: [String] = ids[anyIndex].split(";") // ["ID", "VALUE"]
You can access the ID at index 0 of that array and the value at index 1.
Example:
let id: String = ids[1].split(";")[0]
let code: String = ids[1].split(";")[1]
println("\(id): \(code)") // Piida: bfedsSA

How to Convert an ArrayList to string C#

ArrayList arr = new ArrayList();
string abc =
What should I do to convert arraylist to a string such as abc = arr;Updated QuestOther consideration from which i can complete my work is concatination of string(need help in that manner ). suppose i have a string s="abcdefghi.."by applying foreach loop on it and getting char by matching some condition and concatinating every char value in some insatnce variable of string type i.e string subString=+;Something like thisstring tem = string.Empty;
string temp =string.Empty;
temp = string.Concat(tem,temp);
Using a little linq and making the assumption that your ArrayList contains string types:
using System.Linq;
var strings = new ArrayList().Cast<string>().ToArray();
var theString = string.Join(" ", strings);
Further reading:
http://msdn.microsoft.com/en-us/library/57a79xd0.aspx
For converting other types to string:
var strings = from object o in myArrayList
select o.ToString();
var theString = string.Join(" ", strings.ToArray());
The first argument to the Join method is the separator, I chose whitespace. It sounds like your chars should all contribute without a separator, so use "" or string.Empty instead.
Update: if you want to concatenate a small number of strings, the += operator will suffice:
var myString = "a";
myString += "b"; // Will equal "ab";
However, if you are planning on concatenating an indeterminate number of strings in a tight loop, use the StringBuilder:
using System.Text;
var sb = new StringBuilder();
for (int i = 0; i < 10; i++)
{
sb.Append("a");
}
var myString = sb.ToString();
This avoids the cost of lots of string creations due to the immutability of strings.
Look into string.Join(), the opposite of string.Split()
You'll also need to convert your arr to string[], I guess that ToArray() will help you do that.
Personally and for memory preservation I’ll do for a concatenation:
System.Collections.ArrayList Collect = new System.Collections.ArrayList();
string temporary = string.Empty;
Collect.Add("Entry1");
Collect.Add("Entry2");
Collect.Add("Entry3");
foreach (String var in Collect)
{
temporary = temporary + var.ToString();
}
textBox1.Text = temporary;

Resources