How to extract a pattern of letters from a string? - dart

I have a String 'baseball' and I want to loop on this string and print the output like this:
'b',
'ba',
'bas',
'base',
'baseb',
'baseba',
'basebal',
'baseball'

Just loop through the string and concat the letters and print the result.
String str = "baseball";
String output = "";
for (var i = 0; i < str.length; i++) {
output += str[i];
print(output);
}

I'd create the incremental substrings. If you want to reuse the functionality, perhaps make it a synchronous generator:
Iterable<String> prefixes(String string, {int minLength = 1}) sync* {
for (var i = minLength; i <= string.length; i++) {
yield string.substring(0, i);
}
}
Then you can print them as you want:
for (var prefix in prefixes("baseball")) {
print(prefix);
}

Related

How to create a function WordSplit(strArr) read the array of strings stored in strArr using dart

I have a simple exercise in Coderbyte, it just want to have a function that's WordSplit(strArr) read the array of strings stored in strArr, For example I have two elements like ["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]
I just want to to determine if the first element in the input can be split into two words, where both words exist in the dictionary that is provided in the second input.
For example: the first element can be split into two words: hello and cat because both of those words are in the dictionary.
So the program should return the two words that exist in the dictionary separated by a comma, as this result hello,cat .
I've made a recursive solution below. It checks if the string to be split starts with any word in the dictionary. If it exists, the function is called again using a substring with that first word removed.
This function only works up to the first word that isn't in the dictionary since you did not specify the expected behavior when the inputted word is not made up of words in the dictionary. You could make it throw an exception perhaps, but please specify your expectation.
void main() {
print(wordSplit(["hellocat", "apple,bat,cat,goodbye,hello,yellow,why"]));
//hello,cat
}
String wordSplit(List<String> arg) {
String wordToSplit = arg[0];
String dict = arg[1];
List<String> parsedDict = arg[1].split(',');
for(String word in parsedDict) {
if(wordToSplit.startsWith(word)) {
//If the substring would be empty, don't do more recursion
if(word.length == wordToSplit.length) {
return word;
}
return word + ',' + wordSplit([wordToSplit.substring(word.length), dict]);
}
}
return wordToSplit;
}
#include <bits/stdc++.h>
using namespace std;
vector<string> converToWords(string dict) {
vector<string> res;
string s = "";
int n = dict.length();
for(int i=0; i<n; i++) {
if(dict[i] == ',') {
res.push_back(s);
s = "";
}
else s += dict[i];
}
res.push_back(s);
s = "";
return res;
}
string solve(string str[]) {
string result = "";
string word = str[0], dict = str[1];
int n = word.length();
vector<string> vs = converToWords(dict);
unordered_set<string> ust;
for(auto it: vs) ust.insert(it);
// for(auto i=ust.begin(); i!=ust.end(); i++){
// cout<<*i<<endl;
// }
string s = "";
for(int i=0; i<n; i++) {
s += word[i];
// cout<<s<<endl;
string temp = word.substr(i+1, n-(i+1));
// cout<<temp<<endl;
if(ust.find(s) != ust.end() && ust.find(temp) != ust.end()) {
cout<<s<<endl;
cout<<temp<<endl;
result += s+","+temp;
break;
}
temp = "";
}
return result;
}
int main() {
string arr[2];
cin>>arr[0]>>arr[1];
cout << solve(arr);
return 0;
}

In dart, split string into two parts using length of first string

I have a string hiWorld and
i want to split this string in two parts hi and World by length of first word hi which is of length 2.
This is what i want to do
List<String> list = ("hiWorld").splitFromLength(2);
I'd use the solution you published shortening up the definition:
List<String> splitStringByLength(String str, int length) =>
[str.substring(0, length), str.substring(length)];
or using an extension method to call the function:
extension on String {
List<String> splitByLength(int length) =>
[substring(0, length), substring(length)];
}
'helloWorld'.splitByLength(5); // Returns [hello, World].
My current solution
List<String> splitStringByLength( String str, int length)
{
List<String> data = [];
data.add( str.substring(0, length) );
data.add( str.substring( length) );
return data;
}
This is my solution which is more generic:
List<String> splitByLength(String value, int length) {
List<String> pieces = [];
for (int i = 0; i < value.length; i += length) {
int offset = i + length;
pieces.add(value.substring(i, offset >= value.length ? value.length : offset));
}
return pieces;
}
And the extension method:
extension on String {
List<String> splitByLength(int length, {bool ignoreEmpty = false}) {
List<String> pieces = [];
for (int i = 0; i < this.length; i += length) {
int offset = i + length;
String piece = this.substring(i, offset >= this.length ? this.length : offset);
if (ignoreEmpty) {
piece = piece.replaceAll(RegExp(r'\s+'), '');
}
pieces.add(piece);
}
return pieces;
}
}
You can use it like:
'HELLO WORLD'.splitByLength(5, ignoreEmpty: true)

Dart - find most common character in a string

I'm stuck on this common interview question using Dart. I need to return the most common character in a given string. I'm trying to create a map with a count for each character as the first step.
This is my progress so far:
main(List<String> arguments) {
maxChar('hello');
}
void maxChar(String word) {
Map<String, int> charMap = {};
int max = 0;
String maxChar = '';
word.split('').forEach((char) {
if(charMap.containsValue(char)) {
charMap[char]+1;
return;
} else {
charMap[char] = 1;
}
});
print(charMap);
}
Right now its not even counting the correct amount of the letter 'l'. It's outputting:
{h: 1, e: 1, l: 1, o: 1}
What am I doing wrong? Is there an easier way to return the most common character in a String in Dart?
Thanks!
EDIT:
Ok, I've solved it, but surely there is a more concise way of solving this problem. See my solution below:
main(List<String> arguments) {
print(max_char.maxChar('hello'));
}
String maxChar(String word) {
Map<String, int> charMap = {};
int max = -1;
String maxChar = '';
word.split('').forEach((char) {
if(charMap.containsKey(char)) {
charMap[char]++;
return;
} else {
charMap[char] = 1;
}
});
charMap.forEach((k,v) {
if(v > max) {
max = v;
maxChar = k;
}
});
return maxChar;
}
A shorter approach to counting the characters is definitely possible:
String charCount(String chars) {
int maxChar = -1;
int maxCount = 0;
var counts = <int, int>{};
for (var char in chars.runes) {
int count = counts.update(char, (n) => n + 1, ifAbsent: () => 1);
if (count > maxCount) {
maxCount = count;
maxChar = char;
}
}
return String.fromCharCode(maxChar);
}
If you just want to count the characters, you can remove all the lines mentioning maxCount and maxChar.
I use integers to represent the characters instead of strings. That's cheaper and just as precise, and it allows you to recognize and combine Unicode UTF-16 surrogates.

Compare string in list

I want to match two string in the same list. I want to get words from a string and insert into list. I want to remove white space and separate by commas. Then I want to check two string in that list whether match or not.
Here is my code:
main() {
List<String> list = new List();
String str = "dog , dog , cat, tiger, lion, cat";
String strn = str.replaceAll(" " , "");
list = strn.split(",");
print(list.length);
print(list);
for (int i=0;i<list.length;i++){
if (list[i] == list[i+1]) {
print("same");
} else{
print("not same");
}
i++;
}
}
here string only check upto length 4. and white space not removed!
I also noticed that in the for loop you are incrementing i twice, the second being close to the bottom. This causes i to skip some of the indexes, so loop looks at index 0, then 2, then 4, then it stops.
I have refactored your solution slightly. I removed the second i++ and changed i < list.length to i < list.length - 1 to skip the last item as list[i + 1] will throw an out of range exception:
main() {
List<String> list = new List();
String str = "dog , dog , cat, tiger, lion, cat";
String strn = str.replaceAll(" ", "");
list = strn.split(",");
print(list.length);
print(list.join('|'));
for(int i=0; i < list.length - 1; i++){
if(list[i] == list[i+1]){
print("same");
}
else{
print("not same");
}
}
}
The result of the loop is so:
same
not same
not same
not same
not same
You can test this out on DartPad

Google Dart: Dart strrev() function

I'd like to know if there's any Dart function like PHP's strrev(). If not, could you please show my any source code how to make it on my own?
Thank you.
Lists can be reversed, so you can use this to reverse a String as well:
new String.fromCharCodes("input".charCodes.reversed.toList());
I haven't found one in the API, as a brand new Dart user (as of this afternoon). However, reversing a string is pretty easy to do in any language. Here's the typical O(n) solution in Dart form:
String reverse(String s) {
var chars = s.splitChars();
var len = s.length - 1;
var i = 0;
while (i < len) {
var tmp = chars[i];
chars[i] = chars[len];
chars[len] = tmp;
i++;
len--;
}
return Strings.concatAll(chars);
}
void main() {
var s = "dog";
print(s);
print(reverse(s));
}
May be a standardized reverse() method will be implemented in future in List (dart issue 2804), the following is about 8 to 10 times faster than the previous typical solution:
String reverse(String s) {
// null or empty
if (s == null|| s.length == 0)
return s;
List<int> charCodes = new List<int>();
for (int i = s.length-1; i>= 0; i-- )
charCodes.addLast(s.charCodeAt(i)) ;
return new String.fromCharCodes(charCodes);
}
try this instead of others.
String try(str) {
return str.split('').reversed.join('');
}
String theString = "reverse the string";
List<String> reslt = theString.split("");
List<String> reversedString = List.from(reslt.reversed);
String joinString = reversedString.join("");
print(joinString);
Ouput: gnirts eht esrever

Resources