How to trim leading and trailing spaces from a string in flutter - flutter

I have a 'textformfeild' that takes strings and I want to trim the white spaces at the begining and the end and strict the one in the middle to only one space.
for example if my string is like this:(....AB....CD.....) where the black dots represent the white spaces.
and I wanna make it look like this:(AB.CD)
any idea on how to do that?
this is what I tried to do:
userWeight!.trim()
but this will remove all the white spaces including the one in the middle

trim will remove left and right spaces. You can use RegExp to remove inner spaces:
void main(List<String> args) {
String data = " AB CD ";
String result = data.trim().replaceAll(RegExp(r' \s+'), ' ');
print(result); //AB CD
}

Trim - If you use trim() this will remove only first and end of the white spaces example,
String str1 = " Hello World ";
print(str1.trim());
The output will be only = Hello World
For your purpose you may use replaceAll
String str1 = "....AB....CD.....";
print(str1.replaceAll("....","."));
The output will be = ".AB.CD."
If you still want to remove first and last . use substring
String str1 = "....AB....CD.....";
print(str1.replaceAll("....",".").substring( 1, str1.length() - 1 ));
The output will be = "AB.CD"
This is what your expected output is.

Trim will remove white spaces before and after the string..

Trim will only remove the leading and trailing spaces or white space characters of a given string
Refer this for more:
https://api.flutter.dev/flutter/dart-core/String/trim.html

String str = " AB CD ";
str = str.trim();
while (str.contains(" ")) {
str = str.replaceAll(" ", " ");
}
print(str);

Related

How to replace 2 spaces middle of string to a character and a space in Dart?

I have string as shown below. In dart replaceFirst() its removes all whitespace and it's not what i want. My question is: How to replace 2 spaces middle of string to a character and a space in Dart?
Example:
- Original: String _myText = "abc 23";
- Expected Text: "abcd 23"
- Result with replaceFirst() : "abcd23"
"abc 23".replaceFirst(' ', 'd') returns the expected output.
Use wrap widget may be your problem would be solve
Eg:
Wrap( child:Text(“hii Byy”))
Use below code
String _myText = "abc 23";
_myText.replaceAll(' ', ' '); // it returns the string 'abc 23'
"abc 23".replaceFirst(' ', 'd') returns the expected output. Are you sure, you pass a single white space character and not two as the first parameter of the replaceFirst method ?

Flutter: trim string after certain NUMBER of characters in dart

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

Determine if a string only contains invisible characters in Swift

I was parsing a messy XML. I found many of the nodes contain invisible characters only, for instance:
"\n "
" "
"\t "
"\n "
"\n\n"
I saw some posts and answers about alphabet and numbers, but the XML being parsed in my project includes UTF8 characters. I am not sure how I can list all visible UTF8 characters in the filter.
How can I determine if a string is made up of completely invisible characters like above, so I can filter them out? Thanks!
Use CharacterSet for that.
let nonWhitespace = CharacterSet.whitespacesAndNewlines.inverted
let containsNonWhitespace = (string.rangeOfCharacter(from: nonWhitespace) != nil)
Trim the string of whitespaces and newlines and see what's left.
if someString.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
// someString only contains whitespaces and newlines
}

Swift String including Special Characters

I have a user enter a multi string in an NSTextView.
var textViewString = textView.textStorage?.string
Printing the string ( print(textViewString) ), I get a multi-line string, for example:
hello this is line 1
and this is line 2
I want a swift string representation that includes the new line characters. For example, I want print(textStringFlat) to print:
hello this is line 1\n\nand this is line 2
What do I need to do to textViewString to expose the special characters?
If you just want to replace the newlines with the literal characters \ and n then use:
let escapedText = someText.replacingOccurrences(of: "\n", with: "\\n")

MATLAB: Remove everything after the final blank in a character array

How can I remove all characters after the final blank in a character array?
Input:
ch = {'Test1 Index'; 'Test 2 Index'; 'Test 3 4 Curncy'}
Expected Output:
ch = {'Test1'; 'Test 2'; 'Test 3 4'}
From your example it seems that you want to remove all characters after the final blank, and remove that final blank too.
You can use regexrep as follows:
result = regexprep(ch, '\s\S*$', '');
The regular expression '\s\S*$' matches a blank (\s) followed by zero or more non-blanks (\S*) up to the end of the string ($). The matched substring is replaced by the empty string ('').