How to delete characters from last in a in string in dart? - flutter

I want to remove a character from a string say String A = "Something" Here, I want to make a function that returns "Somethin". Please Help.

void removeLastString() {
String str = "Something";
String result = str.substring(0, str.length - 1);
print(result);
}

Related

flutter how to check if a String contains at least one String from a list of Strings

I want to check if the value that the user enters in a TextFormField contains at least one String in another given String.
As an example, if the given String value is 0123456789 and if the user enters Ab3 in the TextFormField, how to check if the user entered value contains at least one String in the given String?
String allowedChar = "0123456789";
final split = allowedChar.split('');
I tried splitting the given value like this and checked if the textEditingController.text contains the value for each splitted value of allowedChar.
if (_value.isNotEmpty &&
textEditingController.text.contains(c)) {
_areAlwdCharsTyped = true;
} else if (!textEditingController.text.contains(c)) {
_areAlwdCharsTyped = false;
}
But _areAlwdCharsTyped always returns false. Could I know a way to achieve this please? Thanks in advance.
void main() {
const text = 'Ab3';
var match = RegExp(r'\d').hasMatch(text);
print(match);
}
Result
true
I think you're close. You can iteratively check whether the input string contains any of the chars in allowedChars.
void main() {
String allowedChar = "0123456789";
final split = allowedChar.split('');
final str = 'AB3';
final str2 = 'AB';
print(split.fold<bool>(false, (prev, element) => str.contains(element) || prev)); // true
print(split.fold<bool>(false, (prev, element) => str2.contains(element) || prev)); // false
}

Function to iterate trough comma separated hex strings and decode them in dart/flutter

I need a little help with a function in dart/flutter I am trying to write.
There are bunch of HEX encoded strings separated by comma and joined together in one String.
For example:
String input = 'HexEncodedStr1,HexEncodedStr2,HexEncodedStr3'
I need to decode each of those strings and output them in the same comma separated form:
String output = 'HexDecodedStr1,HexDecodedStr2,HexDecodedStr3'
Currently, I am using hex.dart package as string decoder but I am struggling to separate each encoded string before decoding it with hex.dart:
import 'package:hex/hex.dart';
//The decode function
String decode(hexString) {
if (hexString != "") {
hexString = HEX.decode(hexString);
return hexString;
} else {
return "N/A";
}
}
void main() {
String test = decode('776f726c64,706c616e65740d0a');
print(test); //world,planet
}
How about splitting the string and joining decoded parts afterwards?
void main() {
final decoded = '776f726c64,706c616e65740d0a'
.split(',')
.map(decode)
.join(',');
print(decoded); //world,planet
}
You could use string.split(",");
https://api.flutter.dev/flutter/dart-core/String/split.html
String input = 'HexEncodedStr1,HexEncodedStr2,HexEncodedStr3'
var inputSplit = input.split(",");
Now you have a list of substring. I think that you can then you a for loop or foreach.
inputSplit.forEach((element) => print(decode(element);));
or:
for(var i = 0; i < inputSplit.length; i++)
{
var oneHex = decode(inputSplit[i]);
print(oneHex);
}

How to format to json with difference between comma of data/key and comma from text?

I am trying to improve this code so that it can handle a specific case.
Currently it works, unless the user adds a text with a comma
Here is my input who work (look only "note" key/value)
Input_OK = 2020-11-25,note:my text,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
In this case : my text is ok because there is no comma
Input_NOK = 2020-11-25,note:my text, doesn't work,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
In this case : my text, doesn't work is not ok because there is comma
With this specific input 2020-11-25,note:my text, work now,2020-11-25,today:2020-11-25,2020-09-14,start:2020-09-14
I try to have this output
[{"release_date":"2020-11-25","today":"2020-11-25","note0":"my text, work now"},{"release_date":"2020-09-14","start":"2020-09-14"}]
Here is my current code
// before this input I add string to a list<String> for each date like that [2020-11-25,note0:test, 2020-11-24,my text, with comma, 2020-11-15,today:2020-11-15, 2020-09-14,start:2020-09-14]
//After I remove space and [ ]
// myinput 2020-11-25,today:2020-11-25,2020-11-25,note0:my text, with comma,2020-09-14,start:2020-09-14
var inputItarable = myinput.toString().split(',').where((s) => s.isNotEmpty);
print("inputItarable ${inputItarable} ");
//inputItarable [2020-11-25, today:2020-11-25, 2020-11-25, note0:my text, with comma, 2020-09-14, start:2020-09-14]
var i = inputItarable.iterator;
var tmp = {};
while (i.moveNext()) {
var key = i.current; i.moveNext();
var value = i.current.split(':');
(tmp[key] ??= []).add(value);
}
var output1 = tmp.keys.map((key) {
var map = {}; map['release_date'] = key;
tmp[key].forEach((e) => map[e[0]] = e[1]);
return map;
}).toList();
var output2=json.encode(output1);
print("output2 $output2 ");
// output2 [{"release_date":"2020-11-25","today":"2020-11-25","note0":"my text, with comma"},{"release_date":"2020-09-14","start":"2020-09-14"}]
[Edit] I have a spécific case, where user back ligne, and have an input like that
myinput 2020-11-25,today:2020-11-25,2020-11-25,note0:my text,
with comma,2020-09-14,start:2020-09-14
in this example I don't know how to replace the back ligne between my text, and with comma by my text,\nwith comma
Please check the code below or you may directly run it on Dartpad at https://dartpad.dev/1404509cc0b427b1f31705448b5edba3
I have written a sanitize function. What the sanitize function does is it sanitizes the text between the possibleStart and possibleEnd. Meaning it replaces all the commas in user input text with §. To do this it assumes that the user input starts with ,note: or ,note0: and ends with ,2020- or ,2021-. This sanitized string is passed to your code and in the end § is replaced with ",". Let me know if you have any questions.
import 'dart:convert';
String sanitize(
String input, List<String> possibleStart, List<String> possibleEnd) {
final String start = possibleStart.join("|");
final String end = possibleEnd.join("|");
final RegExp exp = RegExp("(?<=$start)(.*?)(?=$end)");
final Iterable<Match> matches = exp.allMatches(input);
matches.forEach((match) {
input =
input.replaceFirst(match.group(0), match.group(0).replaceAll(",", "§"));
return true;
});
return input;
}
void main() {
String myinput =
"2020-11-25,today:2020-11-25,2020-11-25,note0:my text, with comma,2020-09-14,start:2020-09-14";
myinput = sanitize(myinput, [",note:", "note\\d:"], [",20\\d\\d-"]);
var inputItarable = myinput.toString().split(',').where((s) => s.isNotEmpty);
print("inputItarable ${inputItarable} ");
//inputItarable [2020-11-25, today:2020-11-25, 2020-11-25, note0:my text, with comma, 2020-09-14, start:2020-09-14]
var i = inputItarable.iterator;
var tmp = {};
while (i.moveNext()) {
var key = i.current;
i.moveNext();
var value = i.current.split(':');
(tmp[key] ??= []).add(value);
}
var output1 = tmp.keys.map((key) {
var map = {};
map['release_date'] = key;
tmp[key].forEach((e) => map[e[0]] = e[1]);
return map;
}).toList();
var output2 = json.encode(output1).replaceAll("§", ",");
print("output2 $output2 ");
}

trim and remove specific characters from beginning and end of a string in dart

I am looking for a Dart function similar to python's strip function. Remove specific characters only from beginning and end.
String str = "^&%. , !# Hello #World , *%()##$ "
String newStr = str.strip("#*)(#!,^&%.$ ");
Result:
"Hello #World"
You can use a regex to find the length of the leading and trailing part of the string that contain symbols. Then you can make a substring using the indices:
String str = "^&%. ^ , !# Hello# World , *%()##\$ ";
RegExp regex = new RegExp(r'[#*)(#!,^&%.$\s]+');
int leftIdx = regex.stringMatch(str).length;
int rightIdx = regex.stringMatch(str.substring(leftIdx).split('').reversed.join('')).length;
String newStr = str.substring(leftIdx, str.length - rightIdx);
Result:
'Hello# World'
You can write an extension on String like this
void main() {
String str = "^&%. , !# Hello #World , *%()##\$ ";
String newStr = str.strip("#*)(#!,^&%.\$ "); //<== Hello #World
}
extension PowerString on String {
String strip(String whatToStrip){
int startIndex, endIndex;
for(int i = 0; i <= this.length; i++){
if(i == this.length){
return '';
}
if(!whatToStrip.contains(this[i])){
startIndex = i;
break;
}
}
for(int i = this.length - 1; i >= 0; i--){
if(!whatToStrip.contains(this[i])){
endIndex = i;
break;
}
}
return this.substring(startIndex, endIndex + 1);
}
}
This following strip function should remove the special characters as provided.
String strip(String str, String charactersToRemove){
String escapedChars = RegExp.escape(charactersToRemove);
RegExp regex = new RegExp(r"^["+escapedChars+r"]+|["+escapedChars+r']+$');
String newStr = str.replaceAll(regex, '').trim();
return newStr;
}
void main() {
String str = r"^&%. , !# Hello #World , *%()##$ ";
String charactersToRemove = r"#*)(#!,^&%.$ ";
print(strip(str, charactersToRemove));
}
Result:
Hello #World
PS
Raw string can be created by prepending an ‘r’ to a string. It treats $ as a literal character.
If you want to remove whitespaces and special characters , anywhere from the string then try this,
String name = '4 Apple 1 k g ## # price50';
print(name.replaceAll(new RegExp(r'[#*)(#!,^&%.$\s]+'), ""));
Output:- 4Apple1kgprice50

How to insert characters into a Dart String?

I would like to add some white spaces to a Dart String in a given position, exactly like this (In Java).
so...
'XPTOXXSFXBAC' become 'XPTO XXSF XBAC'
Is there an easy way?
You can use the replaceAllMapped method from String, you have to add the regular expression, like this:
final value = "XPTOXXSFXBAC".replaceAllMapped(RegExp(r".{4}"), (match) => "${match.group(0)} ");
print("value: $value");
var x= 'XPTOXXSFXBAC';
x = x.substring(0, 4) + " " + x.substring(4, 8) + " " + x.substring(8, x.length);
print(x) ;
There is a dart package that provides some helper classes for String operations.
Github : https://github.com/Ephenodrom/Dart-Basic-Utils
Install it with:
dependencies:
basic_utils: ^1.5.0
Usage
String s = "";
s = StringUtils.addCharAtPosition("1234567890", "-", 3);
print(s); // "123-4567890"
s = StringUtils.addCharAtPosition("1234567890", "-", 3, repeat: true);
print(s); // "123-456-789-0"
s = StringUtils.addCharAtPosition("1234567890", "-", 12);
print(s); // "1234567890"
Additional information :
These are all methods from the StringUtils class.
String defaultString(String str, {String defaultStr = ''});
bool isNullOrEmpty(String s);
bool isNotNullOrEmpty(String s);
String camelCaseToUpperUnderscore(String s);
String camelCaseToLowerUnderscore(String s);
bool isLowerCase(String s);
bool isUpperCase(String s);
bool isAscii(String s);
String capitalize(String s);
String reverse(String s);
int countChars(String s, String char, {bool caseSensitive = true});
bool isDigit(String s);
bool equalsIgnoreCase(String a, String b);
bool inList(String s, List<String> list, {bool ignoreCase = false});
bool isPalindrome(String s);
String hidePartial(String s, {int begin = 0, int end, String replace = "*"});
String addCharAtPosition(String s, String char, int position,{bool repeat = false});
Your question is unnecessarily specific: you just want to insert characters (or a String) into another Dart String. Whitespace isn't special.
Approach #1
String toSpaceSeparatedString(String s) {
var start = 0;
final strings = <String>[];
while (start < s.length) {
final end = start + 4;
strings.add(s.substring(start, end));
start = end;
}
return s.join(' ');
}
Approach #2 (less efficient)
String toSpaceSeparatedString(String s) {
const n = 4;
assert(s.length % n == 0);
var i = s.length - n;
while (i > 0) {
s = s.replaceRange(i, i, ' ');
i -= n;
}
return s;
}
Approach #2 is less efficient (it needs to repeatedly insert into a String and therefore involves copying the same parts of the String repeatedly) and is more awkward (it iterates from the end of the String to the beginning so that indices are stable), and has more corner cases (for simplicity I'm assuming that the input string is evenly divisible by the substring length). However, I'm including it here because it demonstrates using String.replaceRange, which can be generally useful to insert one String into another, and which probably would be simpler for one-off cases.
I have a simpler version of #diegoveloper's answer by using allMatches. It won't be an extra separator by using join.
final myText = 'XPTOXXSFXBAC';
final separator = ' ';
final result = RegExp(r".{4}")
.allMatches(myText)
.map((e) => e.group(0))
.join(separator);
For Showing Card Number Like 15XX XXXX XXXX 9876 in dart
String num1 = "1567456789099876".replaceAll(RegExp(r'(?<=.{2})\d(?=.{4})'), 'X');
String num = num1.replaceAllMapped(RegExp(r".{4}"), (match) => "${match.group(0)} ");
print(num); //15XX XXXX XXXX 9876