Home > other >  Add space between number and letters in a string dart?
Add space between number and letters in a string dart?

Time:10-16

I want space between the numbers and letters in a string. example: String = "KL11AB2432"; to String = "KL 11 AB 2432";

CodePudding user response:

  String str = "KL11AB2432";
  List<Object> newList = [];

  List<String> strList = str.split("").toList();

  for (var i = 0; i < strList.length; i  ) {
    if (int.tryParse(strList[i]) != null) {
      if ((i - 1) >= 0 && int.tryParse(strList[i - 1]) == null) {
        newList.add(" ");
        newList.add(strList[i]);
      } else {
        newList.add(strList[i]);
      }
    } else {
      if ((i - 1) >= 0 && int.tryParse(strList[i - 1]) != null) {
        newList.add(" ");
        newList.add(strList[i]);
      } else {
        newList.add(strList[i]);
      }
    }
  }

  print(newList);
  print(newList.join().toString());

and Result =>

[K, L, , 1, 1, , A, B, , 2, 4, 3, 2]

KL 11 AB 2432

CodePudding user response:

I am using try catch to check the int type,

bool isInt(String data) {
    try {
      int.parse(data);
      return true;
    } catch (_) {
      return false;
    }
  }

void main() {
  String data = "KL11AB2432";
  bool isPrevIsNum = false;
  bool isPrevIsChar = false;
  String result = "";

  for (int i = 0; i < data.length; i  ) {
    bool isIntData = isInt(data[i]);

    if (isIntData) {
      isPrevIsChar = false;
      if (isPrevIsNum) {
        result = "$result${data[i]}";
      } else {
        result = "$result ${data[i]}";
        isPrevIsNum = true;
      }
    } else {
      isPrevIsNum = false;

      if (isPrevIsChar) {
        result = "$result${data[i]}";
      } else {
        result = "$result ${data[i]}";
      }
      isPrevIsChar = true;
    }
  }

  print(result.trim()); // KL 11 AB 2432
}

Condition can be merged on upper level I think, but to make it clear I've kept like this. There might be others short way

  • Related