Flutter: trim string after certain NUMBER of characters in dart - flutter

Say I have a string with n number of characters, but I want to trim it down to only 10 characters. (Given that at all times the string has greater that 10 characters)
I don't know the contents of the string.
How to trim it in such a way?
I know how to trim it after a CERTAIN character
String s = "one.two";
//Removes everything after first '.'
String result = s.substring(0, s.indexOf('.'));
print(result);
But how to remove it after a CERTAIN NUMBER of characters?

All answers (using substring) get the first 10 UTF-16 code units, which is different than the first 10 characters because some characters consist of two code units. It is better to use the characters package:
import 'package:characters/characters.dart';
void main() {
final str = "Hello πŸ˜€ World";
print(str.substring(0, 9)); // BAD
print(str.characters.take(9)); // GOOD
}
prints
➜ dart main.dart
Hello πŸ˜€
Hello πŸ˜€ W
With substring you might even get half a character (which isn't valid):
print(str.substring(0, 7)); // BAD
print(str.characters.take(7)); // GOOD
prints:
Hello οΏ½
Hello πŸ˜€

The above examples will fail if string's length is less than the trimmed length. The below code will work with both short and long strings:
import 'dart:math';
void main() {
String s1 = 'abcdefghijklmnop';
String s2 = 'abcdef';
var trimmed = s1.substring(0, min(s1.length,10));
print(trimmed);
trimmed = s2.substring(0, min(s2.length,10));
print(trimmed);
}
NOTE:
Dart string routines operate on UTF-16 code units. For most of Latin and Cyrylic languages that is not a problem since all characters will fit into a single code unit. Yet emojis, some Asian, African and Middle-east languages might need 2 code units to encode a single character. E.g. '😊'.length will return 2 although it is a single character string. See characters package.

I think this should work.
String result = s.substring(0, 10);

To trim a String to a certain number of characters. The. code below works perfectly well:
// initialise your string here
String s = 'one.two.three.four.five';
// trim the string by getting the first 10 characters
String trimmedString = s.substring(0, 10);
// print the first ten characters of the string
print(trimmedString);
Output:
one.two.th
i hope this helps

You can do this in multiple ways.
'string'.substr(start, ?length) USE :- 'one.two.three.four.five'.substr(0, 10)
'string'.substring(start, ?end) USE :- 'one.two.three.four.five'.substring(0, 10)
'string'.slice(start, ?end) USE :- 'one.two.three.four.five'.slice(0, 10)

To trim all trailing/right characters by specified characters, use the method:
static String trimLastCharacter(String srcStr, String pattern) {
if (srcStr.length > 0) {
if (srcStr.endsWith(pattern)) {
final v = srcStr.substring(0, srcStr.length - 1 - pattern.length);
return trimLastCharacter(v, pattern);
}
return srcStr;
}
return srcStr;
}
For example, you want to remove all 0 behind the decimals
$123.98760000
then, call it by
trimLastCharacter("$123.98760000", "0")
output:
$123.9876

Related

How to check if a letter is upper/lower cased?- Flutter

The question is pretty self-explainable. I want to check if certain letter is uppercase or another letter is lowercase. Could you give me any examples of how to do that in Flutter/Dart?
you can use the .toUpperCase() in a boolean statement:
bool isUppercased(String str){
return str == str.toUpperCase();
}
If you want to use regular expressions, here is how you could do:
bool isUpperCase(String letter) {
assert(s.length == 1);
final regExp = RegExp('[A-Z]');
return regExp.hasMatch(letter);
}
The one solution that is coming to my mind is to check its ASCII code.
The ASCII code of a-z starts at 97 and ends at 122.
Similarly, in the case of Uppercase letters A-Z it starts from 65 and ends at 90.
Keeping this in mind you can use the method string.codeUnitAt(index) which will return you the ASCII code and later you can check its range and find its an Uppercase or lowercase.
Have a look into this example
main() {
String ch = 'Rose';
print(' ASCII value of ${ch[0]} is ${ch.codeUnitAt(0)}');
print(' ASCII value of ${ch[1]} is ${ch.codeUnitAt(1)}');
}
The output will be:
ASCII value of R is 82
ASCII value of o is 111
Now you can compare with the range using if statement and find out.

Swift 5 split string at integer index

It used to be you could use substring to get a portion of a string. That has been deprecated in favor on string index. But I can't seem to make a string index out of integers.
var str = "hellooo"
let newindex = str.index(after: 3)
str = str[newindex...str.endIndex]
No matter what the string is, I want the second 3 characters. So and str would contain "loo". How can I do this?
Drop the first three characters and the get the remaining first three characters
let str = "helloo"
let secondThreeCharacters = String(str.dropFirst(3).prefix(3))
You might add some code to handle the case if there are less than 6 characters in the string

Counterintuitive result in NumberFormat of Intl Package in Dart/Flutter

Why does NumberFormat(".##").format(17.46) leads to a string of 17.46 and not .46?
How can I achieve the latter, i.e. remove all digits in front of the decimal sign?
The NumberFormat only changes the way that a number is being displayed(basically, what formatting is). So you can't get the fractional part of the number(it doesn't work like pattern matching).
Instead, you can use:
var num = 17.46;
var fraction = num.toString().split('.')[1];
Note: you can use '.' + num.toString().split('.')[1] to get the fraction part with the starting dot.
You can read more about the ICU Formatting that NumberFormat uses in this link.
Just as an alternative to the other answer, you can try to remove the integer part before converting to String, and not after:
String formatFraction (num a){
num b = a.floor();
num c = a-b;
return NumberFormat(".##").format(c);
}
This way you can guarantee it will work despite of locale.
β€˜#’ in the NumberFormat class marks a single digit (omitted if the value is zero). So the number of hashtags after the decimal point denotes how many decimal places you want. For example:
double number = 12.1234;
NumberFormat(".#").format(number); //prints 12.1
NumberFormat(".##").format(number); //prints 12.12
NumberFormat(".###").format(number); //prints 12.123
NumberFormat(".####").format(number); //prints 12.1234
You could use substring and indexOf to remove everything before the decimal point, like so:
String str = "12.36";
String newStr = str.substring(str.indexOf('.') + 1);
//If you want to include the decimal point, remove the + 1.

How to format a number into NN.nn style

I am handling a stream of numbers from sensors and want to format them to a 'standard' layout centered on the decimal point, as per the following: 1.00 = 01.00 | 12.9 = 12.90 | 2 = 02.00 | 49.09 = 49.09 etc.
I have tried zfill and round - including combinations but the decimal point moves in everything I have tried so far. The purpose is to fill pre-defined fields for later analysis.
UPDATE
Probably not the most elegant solution but I came up with this, which works a far as I have been able to test so far:
For padding to the left of decimal point:
def zfl(d, chrs, pad):
# Pads the provided string with leading 'pad's to suit the specified
# 'chrs' length.
# When called, parameters are : d = string, chrs = required length of
# string and pad = fill characters
# The formatted string of correct length and added pad characters is
# returned as string
frmtd_str = str(d)
while len(frmtd_str) != chrs:
# less then required characters
frmtd_str = pad + frmtd_str
return(frmtd_str)`
Function for padding to the right of decimal point:
def zfr(d, chrs, pad):
# Pads the provided string with trailing 'pad's to suit the specified
# 'chrs' length
# When called, parameters are : d = string, chrs = required length of
# string and pad = fill characters
# The formatted string of correct length and added pad characters is
# returned as string
frmtd_str = str(d)
while len(frmtd_str) != chrs:
# less then required characters
frmtd_str = frmtd_str + pad
return(frmtd_str)
Example to call the above funtions:
The original data is split into two parts using the decimal as the seperator:
dat_splt = str(Dat[0]).split(".",2)
Then the padding carried out and reconstructed for use:
exampledat = "{}.{}".format(zfl(dat_splt[0],3,'0'), zfr(dat_splt[1],3,'0'))
Notes:
To pad out either side requires the parameters for string, character required and the 'pad' character.
The characters required can be anything (only tested with 1 to 10)
The final returned string can be asymmetrical i.e. nnnnn.nn or n.nnn
The number of characters in each part of the original data is accommodated.
Quite happy with the results from this and it is reusable as common functions. I am sure there are more 'economical/efficient' methods but I haven't found those yet and at least this works, giving nice orderly and stable text string result lists (which is what I was aiming for at this point).
Hope I got the layout correct.. :-)
'{:0>5.2f}'.format(n)
'{:0>5.2f}'.format(1)
'01.00'
'{:0>5.2f}'.format(12.9)
'12.90'
'{:0>5.2f}'.format(49.09)
'49.09'
https://queirozf.com/entries/python-number-formatting-examples#left-padding-with-zeros

How to split a Korean word into it's components?

So, for example the character κΉ€ is made up of γ„±, γ…£ and ㅁ. I need to split the Korean word into it's components to get the resulting 3 characters.
I tried by doing the following but it doesn't seem to output it correctly:
let str = "κΉ€"
let utf8 = str.utf8
let first:UInt8 = utf8.first!
let char = Character(UnicodeScalar(first))
The problem is, that that code returns Γͺ, when it should be returning γ„±.
You need to use the decomposedStringWithCompatibilityMapping string to get the unicode scalar values and then use those scalar values to get the characters. Something below,
let string = "κΉ€"
for scalar in string.decomposedStringWithCompatibilityMapping.unicodeScalars {
print("\(scalar) ")
}
Output:
α„€
α…΅
α†·
You can create list of character strings as,
let chars = string.decomposedStringWithCompatibilityMapping.unicodeScalars.map { String($0) }
print(chars)
// ["α„€", "α…΅", "α†·"]
Korean related info in Apple docs
Extended grapheme clusters are a flexible way to represent many
complex script characters as a single Character value. For example,
Hangul syllables from the Korean alphabet can be represented as either
a precomposed or decomposed sequence. Both of these representations
qualify as a single Character value in Swift:
let precomposed: Character = "\u{D55C}" // ν•œ
let decomposed: Character = "\u{1112}\u{1161}\u{11AB}" // α„’, α…‘, ᆫ
// precomposed is ν•œ, decomposed is ᄒᅑᆫ