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.
Related
I have two variables
String firstInput = "1.1.5";
String secondInput = "1.1.6";
From this I want the output firstOutput = 115 secondOutput = 116
How to remove dots from the string and concatenate remains as one variable ?
You can use the replaceAll method.
It would look like String out = firstInput.replaceAll(".","");
You can also use replaceAllwith RE as shown below
void main(){
final myString = '1.3.4.6.6';
String withoutDots = myString.replaceAll(RegExp('\\.'), ''); "Here \\ is used to as esc char"
print(withoutDots); // prints 13466
}
Is there a way to split a string by some symbol but only at first occurrence?
Example: date: '2019:04:01' should be split into date and '2019:04:01'
It could also look like this date:'2019:04:01' or this date : '2019:04:01' and should still be split into date and '2019:04:01'
string.split(':');
I tried using the split() method. But it doesn't have a limit attribute or something like that.
You were never going to be able to do all of that, including trimming whitespace, with the split command. You will have to do it yourself. Here's one way:
String s = "date : '2019:04:01'";
int idx = s.indexOf(":");
List parts = [s.substring(0,idx).trim(), s.substring(idx+1).trim()];
You can split the string, skip the first item of the list created and re-join them to a string.
In your case it would be something like:
var str = "date: '2019:04:01'";
var parts = str.split(':');
var prefix = parts[0].trim(); // prefix: "date"
var date = parts.sublist(1).join(':').trim(); // date: "'2019:04:01'"
The trim methods remove any unneccessary whitespaces around the first colon.
Just use the split method on the string. It accepts a delimiter/separator/pattern to split the text by. It returns a list of values separated by the provided delimiter/separator/pattern.
Usage:
const str = 'date: 2019:04:01';
final values = string.split(': '); // Notice the whitespace after colon
Output:
Inspired by python, I've wrote this utility function to support string split with an optionally maximum number of splits. Usage:
split("a=b=c", "="); // ["a", "b", "c"]
split("a=b=c", "=", max: 1); // ["a", "b=c"]
split("",""); // [""] (edge case where separator is empty)
split("a=", "="); // ["a", ""]
split("=", "="); // ["", ""]
split("date: '2019:04:01'", ":", max: 1) // ["date", " '2019:04:01'"] (as asked in question)
Define this function in your code:
List<String> split(String string, String separator, {int max = 0}) {
var result = List<String>();
if (separator.isEmpty) {
result.add(string);
return result;
}
while (true) {
var index = string.indexOf(separator, 0);
if (index == -1 || (max > 0 && result.length >= max)) {
result.add(string);
break;
}
result.add(string.substring(0, index));
string = string.substring(index + separator.length);
}
return result;
}
Online demo: https://dartpad.dev/e9a5a8a5ff803092c76a26d6721bfaf4
I found that very simple by removing the first item and "join" the rest of the List
String date = "date:'2019:04:01'";
List<String> dateParts = date.split(":");
List<String> wantedParts = [dateParts.removeAt(0),dateParts.join(":")];
Use RegExp
string.split(RegExp(r":\s*(?=')"));
Note the use of a raw string (a string prefixed with r)
\s* matches zero or more whitespace character
(?=') matches ' without including itself
You can use extensions and use this one for separating text for the RichText/TextSpan use cases:
extension StringExtension on String {
List<String> controlledSplit(
String separator, {
int max = 1,
bool includeSeparator = false,
}) {
String string = this;
List<String> result = [];
if (separator.isEmpty) {
result.add(string);
return result;
}
while (true) {
var index = string.indexOf(separator, 0);
print(index);
if (index == -1 || (max > 0 && result.length >= max)) {
result.add(string);
break;
}
result.add(string.substring(0, index));
if (includeSeparator) {
result.add(separator);
}
string = string.substring(index + separator.length);
}
return result;
}
}
Then you can just reference this as a method for any string through that extension:
void main() {
String mainString = 'Here was john and john was here';
print(mainString.controlledSplit('john', max:1, includeSeparator:true));
}
Just convert list to string and search
productModel.tagsList.toString().contains(filterText.toLowerCase())
How can I format an integer such as "20190331" to output as "2019-03-31" without firstly converting it to a date and without splitting it using substring. The date is stored as an integer in SQLite (SQFlite). I would like to do it in 1 line such as (pseudo code) Note: integer :
(pseudo) String sDate = fmt("####'-'##'-'##", map["DueDate"]);
I know that I could do it such as :
String sDate = map["DueDate"].toString();
sDate = sDate.substring(0,4)+'-'+sDate.substring(4,6)+'-'+sDate.substring(6,8);
That however is two lines of code, and Visual Studio Code turns it into 8 lines when formatted and I like to keep my code compact.
Write a function called fmt and call it as in your pseudo code.
String fmt(String f, int i) {
StringBuffer sb = StringBuffer();
RuneIterator format = RuneIterator(f);
RuneIterator input = RuneIterator(i.toString());
while (format.moveNext()) {
var currentAsString = format.currentAsString;
if (currentAsString == '#') {
input.moveNext();
sb.write(input.currentAsString);
} else {
sb.write(currentAsString);
}
}
return sb.toString();
}
one line:
print(fmt('####-##-##', 20190331));
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]}';
});
}
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);