Home > Software engineering >  String transformation for subject course code for Dart/Flutter
String transformation for subject course code for Dart/Flutter

Time:11-25

For interaction with an API, I need to pass the course code in <string><space><number> format. For example, MCTE 2333, CCUB 3621, BTE 1021.

Yes, the text part can be 3 or 4 letters.

Most users enter the code without the space, eg: MCTE2333. But that causes error to the API. So how can I add a space between string and numbers so that it follows the correct format.

CodePudding user response:

You can achieve the desired behaviour by using regular expressions:

void main() {
  String a = "MCTE2333";

  String aStr = a.replaceAll(RegExp(r'[^0-9]'), ''); //extract the number
  String bStr = a.replaceAll(RegExp(r'[^A-Za-z]'), ''); //extract the character
  print("$bStr $aStr"); //MCTE 2333 
}

Note: This will produce the same result, regardless of how many whitespaces your user enters between the characters and numbers.

CodePudding user response:

Here is the entire logic you need (also works for multiple whitespaces!):

 void main() {
  
 String courseCode= "MMM      111";
 String parsedCourseCode = "";
  
 if (courseCode.contains(" ")) {
    final ensureSingleWhitespace = RegExp(r"(?! )\s | \s ");
    parsedCourseCode = courseCode.split(ensureSingleWhitespace).join(" ");
 } else {
    final r1 = RegExp(r'[0-9]', caseSensitive: false);
    final r2 = RegExp(r'[a-z]', caseSensitive: false);
    final letters = courseCode.split(r1);
    final numbers = courseCode.split(r2);
    parsedCourseCode = "${letters[0].trim()} ${numbers[3]}";
 }
   print(parsedCourseCode);  
}

Play around with the input value (courseCode) to test it - also use dart pad if you want. You just have to add this logic to your input value, before submitting / handling the input form of your user :)

CodePudding user response:

Try this.You have to give two texfields. One is for name i.e; MCTE and one is for numbers i.e; 1021. (for this textfield you have to change keyboard type only number).

After that you can join those string with space between them and send to your DB. It's just like hack but it will work.

CodePudding user response:

You can use tryParse to check index value type and then parse

main(List<String> args) {
  String data = 'MCTR 2333';

  late String result;

  if (data.contains("")) {
    result = data;
  }
  if (int.tryParse(data[3]) != null) {
    result = data.substring(0, 3)   " "   data.substring(3, data.length);
  } else {
    result = data.substring(0, 4)   " "   data.substring(4, data.length);
  }

  print(result);
}

  • Related