String transformation for subject course code for Dart/Flutter

Viewed 129

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.

4 Answers

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.

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.

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.last}";
 }
   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 :)

Scrolling down the course codes list, I noticed some unusual formatting.

Example: TQB 1001E, TQB 1001E etc. (With extra letter at the end)

So, this special format doesn't work with @Jahidul Islam's answer. However, inspired by his answer, I manage to come up with this logic:

var code = "TQB2001M";
var i = course.indexOf(RegExp(r'[^A-Za-z]')); // get the index
var j = course.substring(0, i); // extract the first half
var k = course.substring(i).trim(); // extract the others
var formatted = '$j $k'.toUpperCase(); // combine & capitalize
print(formatted); // TQB 1011M

Works with other formats too. Check out the DartPad here.

Related