String of fixed length digits in Bogus - bogus

I did this:
var f = new Faker();
String.Join("", f.Random.Digits(10)
However, is there another method that would eliminate the 'Join' call?

Wow. Sorry for the late reply, but yes there's a way to do this in Bogus.
void Main()
{
var f = new Faker();
var numberString = f.Random.ReplaceNumbers("##########");
numberString.Dump();
}
OUTPUT:
2166951396
By the way, thanks for using Bogus!

Related

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]}';
});
}

Is there a built-in method to pad a string?

I'm trying to add zero-padding to a number. I did some searching and can't find an obvious way to do this. Am I missing something?
Dart 1.3 introduced a String.padLeft and a String.padRight you can use :
String intToString(int i, {int pad 0}) => i.toString().padLeft(pad, '0');
You can use the String function .padLeft(Int width, [String = ' '])
https://api.dartlang.org/apidocs/channels/dev/dartdoc-viewer/dart-core.String#id_padLeft
int i = 2;
print(i.toString().padLeft(2, "0"));
result: 02
I don't think you're missing anything, there's a big lack of formatting functions right now. I think the best you can do is something like:
String intToString(int i, {int pad: 0}) {
var str = i.toString();
var paddingToAdd = pad - str.length;
return (paddingToAdd > 0)
? "${new List.filled(paddingToAdd, '0').join('')}$i" : str;
}
Obviously something that took a format string would be much nicer. Feature request?

Where is Math.round() in Dart?

I don't see any way to round a number in Dart?
import 'dart:math';
main() {
print(Math.round(5.5)); // Error!
}
http://api.dartlang.org/docs/bleeding_edge/dart_math.html
Yes, there is a way to do this. The num class has a method called round():
var foo = 6.28;
print(foo.round()); // 6
var bar = -6.5;
print(bar.round()); // -7
In Dart, everything is an object. So, when you declare a num, for example, you can round it through the round method from the num class, the following code would print 6
num foo = 5.6;
print(foo.round()); //prints 6
In your case, you could do:
main() {
print((5.5).round());
}
This equation will help you
int a = 500;
int b = 250;
int c;
c = a ~/ b;
UPDATE March 2021:
The round() method has moved to https://api.dart.dev/stable/2.12.2/dart-core/num/round.html. All the above links are wrong.
Maybe this can help in specific situations, floor() will round towards the negative infinite
https://api.dart.dev/stable/2.13.4/dart-core/num/floor.html
void main() {
var foo = 3.9;
var bar = foo.floor();
print(bar);//prints 3
}

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

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