I am trying to find if two phone numbers are same or not (Two same phone number may not be in the same format, as +919998245345 is same as 9998245345 and 99982 45345)
For this, you can use contains() dart string method. I have marked the trailing statement as bold, cos, it applies on the String. Make sure you get the number in String format, or convert it to String and then perform the operation.
Alogrithm
Convert the number to be compared to String, or get the number as String
Remove all the white spaces using this code, your_phone_number_variable.replaceAll(new RegExp(r"\s+"), ""). So that every number should be having no white spaces in between for smooth operation
Use contains() like this, number1.contains(number2)
Code
// this is a comparision between +919998245345 and other numbers
// you can play around and get what you want
void main() {
var _inputPhone = "+919998245345";
var _checkPhone = "9998245345";
var _anotherCheck = "99982 45345";
// checking that white space removal works or not
print(_anotherCheck.replaceAll(new RegExp(r"\s+"), ""));
// I have just removed the spaces from the number which had the white
// space, you can store the value using this code for every data
// for unknown data coming from server side or user side
_anotherCheck = _anotherCheck.replaceAll(new RegExp(r"\s+"), "");
if(_inputPhone.contains(_anotherCheck)){
print('99982 45345 and +919998245345 are same');
}
if(_inputPhone.contains(_checkPhone)){
print('9998245345 and +919998245345 are same');
}
}
Output
9998245345
99982 45345 and +919998245345 are same
9998245345 and +919998245345 are same
void main() {
print(isSame('9998245345', '+91999824 5345'));
}
bool isSame(String number1, String number2) {
number1 = number1.replaceAll(' ', '');
number2 = number2.replaceAll(' ', '');
int len1 = number1.length;
int len2 = number2.length;
number1 = number1.substring(len1-10, len1);
number2 = number2.substring(len2-10, len2);
return number1 == number2;
}
I think this is the simple and best solution to chnage format of phone
String changeFormat(String phone) {
phone = phone.replaceAll(" ", "");
if (phone.startsWith("+")) {
return "0" + phone.substring(3);
} else {
return phone;
}
}
Related
As part of the app I am shortening a user-given string to 40 characters and appending ellipses at the end if the string is longer than 40 characters. The users are allowed/able to use emoji in their strings.
If a string that is cut off has an emoji at the 40-character mark it causes it to fail to render and renders as a "�".
Is there a way to reliably get a sub-string of a text but without running into this issue?
Current code:
if (useStr.length > 40) {
useStr = useStr.substring(0, 40) + "...";
}
You should use package:characters and truncate strings based on graphemes (human-perceived characters) and not on (UTF-16) code units.
import 'package:characters/characters.dart';
void main() {
final originalString = '\u{1F336}\uFE0F' * 3; // 🌶️🌶️🌶️
const ellipsis = '\u2026';
for (var i = 1; i < 4; i += 1) {
var s = originalString;
var characters = s.chararacters;
if (characters.length > i) {
s = '${characters.take(i)}$ellipsis';
}
print(s);
}
}
which prints:
🌶️…
🌶️🌶️…
🌶️🌶️🌶️
I am working on application to show mobile contact list with initials in a circle, but not getting initial character for some contact names.
In below code, first name is from mobile's contact list and second one I have typed from keyboard.
I am able to get correct length and also first character of the second name, but length for first name is double and also not able to get first character (it gives �).
print("𝙽𝚊𝚐𝚎𝚜𝚑".substring(0,1)); //�
print("𝙽𝚊𝚐𝚎𝚜𝚑".length); //12
print("Nagesh".substring(0,1)); //N
print("Nagesh".length); //6
Thankyou in advance for answering....
You can use this function to use substring with unicode:
subOnCharecter({required String str, required int from, required int to}) {
var runes = str.runes.toList();
String result = '';
for (var i = from; i < to; i++) {
result = result + String.fromCharCode(runes[i]);
}
return result;
}
and you can use it like this:
print(subOnCharecter(str: "𝙽𝚊𝚐𝚎𝚜𝚑", from: 0, to: 2)); // 𝙽𝚊
print(subOnCharecter(str: "Nagesh", from: 0, to: 2)); // Na
you can use this function instead of default substring.
The strings look similar, but they consist of different unicode characters.
Character U+1d67d "𝙽" is not the same as U+004e "N".
You can use str.runes.length to get the number of unicode characters.
A detailed explanation why the string length is different can be found here
example:
void main() {
var mobileStr = "𝙽𝚊𝚐𝚎𝚜𝚑";
var keyboardStr = "Nagesh";
analyzeString(mobileStr);
print("");
analyzeString(keyboardStr);
}
void analyzeString(String s) {
Runes runes = s.runes; // Unicode code-points of this string
var unicodeChars = runes.map((r) => r.toRadixString(16)).toList();
print("String: $s");
print("String length: ${s.length}");
print("Number of runes: ${runes.length}");
print("unicode characters: ${unicodeChars.join(" ")}");
}
// OUTPUT
// String: 𝙽𝚊𝚐𝚎𝚜𝚑
// String length: 12
// Number of runes: 6
// unicode characters: 1d67d 1d68a 1d690 1d68e 1d69c 1d691
// String: Nagesh
// String length: 6
// Number of runes: 6
// unicode characters: 4e 61 67 65 73 68
I guess it is not possible to parse a date in "MMddyy" format in dart.
void main() {
String strcandidate = "031623";
String format = "MMddyy";
var originalFormat = DateFormat(format).parse(strcandidate);
}
Output:
Uncaught Error: FormatException: Trying to read dd from 031623 at position 6
The following works fine when parsing a date in "MM-dd-yy" format.
void main() {
String strcandidate = "03-16-23";
String format = "MM-dd-yy";
var originalFormat = DateFormat(format).parse(strcandidate);
}
In the problem, the input date string can be in any format e.g ['yyyy-MM-dd', 'MMM'-yyyy, 'MM/dd/yy']. I am parsing the input string for these formats in a loop as follows.
dateFormatsList = ['yyyy-MM-dd', 'MMM'-yyyy, 'MM/dd/yy'];
for (String format in dateFormatsList ) {
try {
originalFormat = DateFormat(format).parse(strcandidate);
dateFound = true;
} catch (e) {}
}
Adding 'MMddyy' to dateFormatsList is not going to work.
But regular expression be used to parse this format.
However if all formats are parsed using parse method and one additional format is parsed using regular expression, then the code is not that neat, and cluttered.
To write as much neat and efficient code as possible, if you want, you can share your insights about any possibility for making it efficient and clean while incorporating 'MMddyy'format. Tysm!
See How do I convert a date/time string to a DateTime object in Dart? for how to parse various date/time strings to DateTime objects.
If you need to mix approaches, you can provide a unified interface. Instead of using a List<String> for your list of formats, you can use a List<DateTime Function(String)>:
import 'package:intl/intl.dart';
/// Parses a [DateTime] from [dateTimeString] using a [RegExp].
///
/// [re] must have named groups with names `year`, `month`, and `day`.
DateTime parseDateFromRegExp(RegExp re, String dateTimeString) {
var match = re.firstMatch(dateTimeString);
if (match == null) {
throw FormatException('Failed to parse: $dateTimeString');
}
var year = match.namedGroup('year');
var month = match.namedGroup('month');
var day = match.namedGroup('day');
if (year == null || month == null || day == null) {
throw ArgumentError('Regular expression is malformed');
}
// In case we're parsing a two-digit year format, instead of
// parsing the strings ourselves, reparse it with [DateFormat] so that it can
// apply its -80/+20 rule.
//
// [DateFormat.parse] doesn't work without separators, which is why we
// can't use directly on the original string. See:
// https://github.com/dart-lang/intl/issues/210
return DateFormat('yy-MM-dd').parse('$year-$month-$day');
}
typedef DateParser = DateTime Function(String);
DateParser dateParserFromRegExp(String rePattern) =>
(string) => parseDateFromRegExp(RegExp(rePattern), string);
var parserList = [
DateFormat('yyyy-MM-dd').parse,
DateFormat('MMM-yyyy').parse,
DateFormat('MM/dd/yy').parse,
dateParserFromRegExp(
r'^(?<month>\d{2})(?<day>\d{2})(?<year>\d{4})$',
)
];
void main() {
var strcandidate = '12311776';
DateTime? originalFormat;
for (var tryParse in parserList) {
try {
originalFormat = tryParse(strcandidate);
break;
} on Exception {
// Try the next format.
}
}
print(originalFormat);
}
I think it's a bit hacky but what about use a regular expression (RegExp) to parse the date divider and then replace it with just ""?
void main() {
String strcandidate = "031623";
String strYear = strcandidate.substring(4);
//Taken 20 as the year like 2023 as year is in 2 digits
String _newDateTime = '20' + strYear + strcandidate.substring(0, 4);
var _originalFormat = DateTime.parse(_newDateTime);
print(_originalFormat);
}
add the intl to yaml then write this code:
import 'package:intl/intl.dart';
void main() {
var strcandidate = DateTime(2023, 3, 16);
String format = "MMddyy";
var originalFormat = DateFormat(format).format(strcandidate);
print(originalFormat);
}
Is there a way to format a number :
from 1 to 1.00,
from 2.5 to 2.50,
from 2.1234 to 2.1234
so basically the number will have a minimum of 2 decimal places
Thanks for your help.
A non elegant way using Intl package:
var f = NumberFormat('#.00###############', 'en_Us');
print(f.format(2.123400))
and you will get
2.1234
but if your number have more decimal digit than you have '#' in format string then it's not show.
For example
var f = NumberFormat('#.00##', 'en_Us');
print(f.format(2.123456))
you will get
2.1234
I think that way works most of cases.
Or you can make format function by yourself. Like this:
String formatNumber(double number) {
int precision = 0;
while ((number * pow(10, precision)) % 10 != 0) {
precision++;
}
return number.toStringAsFixed(max(precision - 1, 2));
}
In this case you don't use Intl package. There is no problem with number of digit after dot. BUT i belive that is a much slower than using intl package.
The Intl package has a set of formatting classes than can help with this use case in particular the NumberFormat Class
you can use someDoubleValue.toStringAsFixed(2) what this does is it basically adds or removes floating points from value
Note: if you parse double from this result string again, it will convert back (5.00 => 5)
Example:
String parseNumber(value) {
String strValue = value.toString();
List parsedNumber = strValue.split(".");
String newValue;
if (parsedNumber.length == 1) {
newValue = value.toStringAsFixed(2);
} else {
String decimalPlace = parsedNumber[1];
if (decimalPlace.length > 2) {
newValue = value.toString();
} else {
newValue = value.toStringAsFixed(2);
}
}
return newValue;
}
I have data from database "192624". how I can change the String format in flutter become time formatted. example "192624" become to "19:26:24". I try using intl packages is not my hope result.
this my code
DateTime inputDate = inputDate;
String formattedTime = DateFormat.Hms().format(inputDate);
in above is not working
I want result convert data("192624") to become "19:26:24". data time from database.
use this method
String a() {
var a = "192624".replaceAllMapped(
RegExp(r".{2}"), (match) => "${match.group(0)}:");
var index = a.lastIndexOf(":");
a = a.substring(0,index);
return a;
}
Have you checked out this a answer :
String time;
// call this upper value globally
String x = "192624";
print(x.length);
x = x.substring(0, 2) + ":" + x.substring(2, 4)+":"+x.substring(4,x.length);
time =x;
print(x);
just globally declare the string and then assign the local String to global then call it in the ui