13

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?

alexpfx
  • 6,412
  • 12
  • 52
  • 88

6 Answers6

37

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");
diegoveloper
  • 93,875
  • 20
  • 236
  • 194
  • a little more verbose than I expected, but thanks :) – alexpfx Jul 02 '19 at 22:13
  • But there is one issue if we separate using "-" then it will add - at the end of the string – Dhiroo Verma Oct 06 '21 at 05:30
  • This will add an extra space at the end of the string. To prevent that, use `trimRight()` method. `"XPTOXXSFXBAC".replaceAllMapped(RegExp(r".{4}"), (match) => "${match.group(0)} ").trimRight()`. If you are using a character different than space, use `str.substring(0, str.length - 1)` – Murali Krishna Regandla Jan 10 '22 at 07:43
21
 var x= 'XPTOXXSFXBAC';
 x = x.substring(0, 4) + " " + x.substring(4, 8) + " " + x.substring(8, x.length);
 print(x) ;
David
  • 15,894
  • 22
  • 55
  • 66
  • This is only useful if you know the String will always be 12 long. What if you have a String longer or shorter? Will it become ABC DEF GHIJKLMNOPQRST? – SilkeNL Apr 14 '22 at 13:16
17

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});
Ephenodrom
  • 1,797
  • 2
  • 16
  • 28
5

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.

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
2

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);
GrayH
  • 61
  • 2
1

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
Techalgoware
  • 540
  • 6
  • 11