Get Common substring between list and string Flutter - dart

Sample 1:
tags = ['what','play','school']
string = "what is your name?"
Output = ['what']
Sample 2:
tags = ['what is','play football','school','food']
string = "what is your school name? Do you play football there?"
Output = ['what is','school',"play football"]
How can I achieve this in flutter?

You can use where to find all words present in the string.
void main() {
List<String> tags = ['what', 'play', 'school'];
String _string = "what is your name?";
List<String> commonWords = [...tags.where(_string.contains)];
print(commonWords); // [what]
}

void main() {
var tags = ['what is', 'play football', 'school', 'food'];
String string = "what is your school name? Do you play football there?";
print(tags.where((element)=> string.contains(element)));
}

Related

Dart syntax of ".."

I have a question in Dart, as follows:
void main() {
String originUrl = "http://www.123.com?name={0}&age={1}";
String newUrl = originUrl.replaceFirst('{0}', 'Jack')
..replaceFirst('{1}', '20');
print(newUrl);
}
output:
http://www.123.com?name=Jack&age={1}
Why not below:
http://www.123.com?name=Jack&age=20
In your code you don't need to use the cascade operator, using that you won't get the String returned by replaceFirst('{1}', '20').
it should look like this:
// Replace {0} with Jack, and return a new String
String newUrl = originUrl.replaceFirst('{0}', 'Jack')
.replaceFirst('{1}', '20'); //Replace {1} with 20 in the last string and return a new String.

How to format an interploated String

I need format string like "Send %d seconds ago", "Harry like %s", "I think %1$s like %2$s". These can be implemented in Android, but i don't how to implement in Dart of Flutter.
Dart supports string interpolation
var seconds = 5;
print("Send $seconds seconds ago");
var harryLikes = 'Silvia';
var otherName = 'Erik';
var otherLikes = 'Chess';
print("Harry like $harryLikes");
print("I think $otherName like $otherLikes");
Also more complex expressions can be embedded with ${...}
print('Calc 3 + 5 = ${3 + 5}');
The number types and the intl package provide more methods to format numbers and dates.
See for example:
https://www.dartdocs.org/documentation/intl/latest/intl/NumberFormat-class.html
Currency format in dart
Add the following to your pubspec.yaml
dependencies:
sprintf: "^5.0.0"
then run pub install.
Next, import dart-sprintf:
import 'package:sprintf/sprintf.dart';
Example #
import 'package:sprintf/sprintf.dart';
void main() {
double seconds = 5.0;
String name = 'Dilki';
List<String> pets = ['Cats', 'Dogs'];
String sentence1 = sprintf('Sends %2.2f seconds ago.', [seconds]);
String sentence2 = sprintf('Harry likes %s, I think %s likes %s.', [pets[0], name, pets[1]]);
print(sentence1);
print(sentence2);
}
Output
Sends 5.00 seconds ago.
Harry likes Cats, I think Dilki likes Dogs.
Source: https://pub.dartlang.org/packages/sprintf
If you want String interpolation similar to Android (Today is %1$ and tomorrow is %2$), you can create a top level function, or an extension that can do something similar. In this instance I keep it similar to Android strings as I'm currently porting an Android app (Interpolatation formatting starts with 1 rather than 0)
Top Level Function
String interpolate(String string, List<String> params) {
String result = string;
for (int i = 1; i < params.length + 1; i++) {
result = result.replaceAll('%${i}\$', params[i-1]);
}
return result;
}
You can then call interpolate(STRING_TO_INTERPOLATE, LIST_OF_STRINGS) and you string would be interpolated.
Extensions
You can create an extension function that does something similarish to Android String.format()
extension StringExtension on String {
String format(List<String> params) => interpolate(this, params);
}
This would then allow you to call text.format(placeHolders)
Testing
Couple of tests for proof of concent:-
test('String.format extension works', () {
// Given
const String text = 'Today is %1\$ and tomorrow is %2\$';
final List<String> placeHolders = List<String>()..add('Monday')..add('Tuesday');
const String expected = 'Today is Monday and tomorrow is Tuesday';
// When
final String actual = text.format(placeHolders);
// Then
expect(actual, expected);
});
Like already stated, I also use the sprintf package but along with a handy extension of the String class.
So after adding the package dependency sprintf: "^4.0.0" to your dependencies list in pubspecs.yaml, create a new Dart-file containing the extension for the Spring class contributing a format method like this:
extension StringFormatExtension on String {
String format(var arguments) => sprintf(this, arguments);
}
Now after you import the dart file containing the StringFormatExtension extension, you can type something like:
String myFormattedString = 'Hello %s!'.format('world');
Feels like in Java (where I come from).
I did it the old fashioned way
String url = "https://server.com/users/:id:/view";
print(url.replaceAll(":id:", "69");
you could also have something simple like this:
Usage
interpolate('Hello {#}{#}, cool {#}',['world','!','?']);
// Hello world!, cool ?
Function
static const needleRegex = r'{#}';
static const needle = '{#}';
static final RegExp exp = new RegExp(needleRegex);
static String interpolate(String string, List l) {
Iterable<RegExpMatch> matches = exp.allMatches(string);
assert(l.length == matches.length);
var i = -1;
return string.replaceAllMapped(exp, (match) {
print(match.group(0));
i = i + 1;
return '${l[i]}';
});
}

Using delimeter to seperate Scanner input into different dataTypes.(String, int,

how can i use delimiter " : " to receive a string from (system.in ) E.g Ben : 50. Jessica : 30 and so on , and then print as Ben, 50 using my own System.out.print (name + "," + score); I was able to print out the string as string but its not printing out the integer as integer. I need to calculate the average of all the score and that is why i need integer to remain integer so the average method can work Here is my code . Here is my code so far. Please help !!!
-------------------------------------------------------------------------
import java.util.Scanner;
public class StudentScore{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
input.useDelimiter(":");
System.out.print("Please enter your name and score in format: Ben : 50" );
String name = input.next();
int score = input.nextInt();
while(input.hasNext() || input.hasNextInt());{
System.out.println(name + ", " + score);
}
input.close();
}
}
this keeps creeating a new scanner and no print out.
After researching and asking several people , i found out the String class actually has a function that takes in string and then splits it into several primitive values" long", " int" and so on. You need to convert your input into an array, make sure it is spitted by a delimiter of choice .e.g "," or ":" in my own case. Then the array will be your parameter for the .split method from the String class. I posted my complete program below. The programs takes in three names and score and outputs the grade letter and then tells the best score among the three students.
import java.util.Scanner;
public class ThreeNamesAndScore {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name and score in this format, Name : Score");
String input1 = input.nextLine();
String[] userData1 = input1.split(":");
String firstStudentName = userData1[0];
String firstStudentStrScore = userData1[1];
int firstStudentScore = Integer.parseInt(firstStudentStrScore);
System.out.print("Please enter your name and score in this format, Name : Score");
String input2 = input.nextLine();
String[] userData2 = input2.split(":");
String secondStudentName = userData2[0];
String secondStudentStrScore = userData2[1];
int secondStudentScore = Integer.parseInt(secondStudentStrScore);
System.out.print("Please enter your name and score in this format, Name : Score");
String input3 = input.nextLine();
String[] userData3 = input3.split(":");
String thirdStudentName = userData3[0];
String thirdStudentStrScore = userData3[1];
int thirdStudentScore = Integer.parseInt(thirdStudentStrScore);
System.out.println("The following is the fianl result ");
System.out.println(firstStudentName + ", " + getGradeLetter(firstStudentScore));
System.out.println(secondStudentName + ", " + getGradeLetter(secondStudentScore));
System.out.println(thirdStudentName + ", " + getGradeLetter(thirdStudentScore));
System.out.println("The best score is from " + bestScore(input1, input2, input3));
input.close();
}
public static String getGradeLetter(int score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else if (score >= 60) {
return "D";
} else
return "F";
}
public static String bestScore(String a, String b, String c) {
String bestStudent;
String[] userInputs = { a, b, c };
String[] user1 = a.split(":");
String aStrScore = user1[1];
int aScore = Integer.parseInt(aStrScore);
String[] user2 = b.split(":");
String bStrScore = user2[1];
int bScore = Integer.parseInt(bStrScore);
String[] user3 = c.split(":");
String cStrScore = user3[1];
int cScore = Integer.parseInt(cStrScore);
if ((aScore > bScore) && (aScore > cScore))
bestStudent = a;
else if ((bScore > aScore) && (bScore > cScore))
bestStudent = b;
else
bestStudent = c;
return bestStudent;
}
}

Swift checking String for guid value

I receive from my web service an authorisation string, that represents a Guid (C#). How I can convert string into guid using Swift? Or, how I can validate result, that it is, in fact, a Guid?
var str1:String = "5810744d-49f7-4edc-aefb-ecd1ebf9e59b"
var str2:String = "Some text"
How i can define - is string contains guid?
You can use NSPredicate with a regex to see if a string is in the correct format:
var str1:String = "(5810744d-49f7-4edc-aefb-ecd1ebf9e59b)"
var str2:String = "Some text"
let guidPred = NSPredicate(format: "SELF MATCHES %#", "((\\{|\\()?[0-9a-f]{8}-?([0-9a-f]{4}-?){3}[0-9a-f]{12}(\\}|\\))?)|(\\{(0x[0-9a-f]+,){3}\\{(0x[0-9a-f]+,){7}0x[0-9a-f]+\\}\\})")
// Prints "str1 IS a GUID"
if guidPred.evaluateWithObject(str1) {
println("str1 IS a GUID")
} else {
println("str1 is NOT a GUID")
}
// Prints "str2 is NOT a GUID"
if guidPred.evaluateWithObject(str2) {
println("str2 IS a GUID")
} else {
println("str2 is NOT a GUID")
}
This regex will match any of the four formats listed on MSDN. To keep it (relatively) simple, the expression will match some ill-formatted strings (such as if you were to delete one hyphen, but not all the others: 5810744d49f7-4edc-aefb-ecd1ebf9e59b), but will filter out regular text.

Extract More than 3 Words After the First Word

In the app I'm working on, I need to extract the first word from a String and put it into another String and the rest of the words in yet another String. I was able to extract the first word using:
String pString = "KOF0000094 Implementation:ListingRequest:User FO-Partner"
int spacePos3 = pString.indexOf(" ");
String pFirstWord = pString.substring(0,spacePos3);
Result : KOF0000094
Now I want the "Implementation:ListingRequest:User FO-Partner" to put
in another String.
Thanks for your help in advance
Simplest solution with what you already have.
String restOfString = pString.substring(spacePos3+1)
String pSecondWord = pString.substring(spacePos3 + 1);
String whole = "KOF0000094 Implementation:ListingRequest:User FO-Partner";
String firstWord = "";
String restOfWords = "";
int spacesIndex = whole.indexOf(" ", 0);
restOfWords = whole.substring(spacesIndex, whole.length());
restOfWords = restOfWords.trim();
firstWord = whole.substring(0, spacesIndex);
firstWord = firstWord.trim();
This is simple string parsing... just find the first index of the first space... i.e. in a for loop...
if(string.charAt(i) == Characters.SPACE)
indexOfSpace = i;
Then your first word will be
String part1 = string.substring(0,indexOfSpace);
and the second string will be
String part2 = string.substring(indexOfSpace + 1);
Try using another call to substring(). What is the index of the first character in the string you want? What is the index of the last character?
You already have the index of the first space, which marks the end of the first word, so all you need to do is take the substring from the index immediately after that (so you don't include the space itself) to the end of the string.
You're probably better of using the split function
It would look something like this:
String pString = "KOF0000094 Implementation:ListingRequest:User FO-Partner";
String[] parts = pString.split(" ");
String partone = parts[0];
String partwo = parts[1] + " " +parts[2];
Or something similar, if there are going to be more spaces in the part following the first word you could use a loop or something similar;
You could use split, for instance...
static String pString = "KOF0000094 Implementation:ListingRequest:User FO-Partner";
static String[] pFirstWord = pString.split(" ");
/**
* #param args
*/
public static void main(String[] args) {
for(String word : pFirstWord) {
System.out.println(word);
}
}
This returned...
KOF0000094
Implementation:ListingRequest:User
FO-Partner
So the last string would be pFirstWord[1] + pFirstWord[2]
String class has a split method: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#split(java.lang.String)
Use that if you want to get all the words.
EDIT: as mentioned in the comments, String.split is not supported in BB Java.
Or this if you just want the first word and the rest of the string:
int index=yourstring.indexOf(" ");
String firstWord = yourstring.substring(0,index);
String rest = yourstring.substring(index+1);

Resources