Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

remove special index character from string | flutter

I want to remove the the 3rd character, If the 3rd character(index) of the String is "0".

for example

String a = "850666";
String b = "8526668";

I want to get 85666 as "a" and 8526668 as "b"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(Length of Strings are not same)

My try:

void checkNumber(String loginToken) {
    if (loginToken[3] == "0") {
      String first = loginToken.substring(0, 2);
      String nd = loginToken.substring(4, loginToken.length - 1);
      String finalone = first + nd;
      showSnackBarGreen(context, finalone, finalone);
    }
  }

It does not work perfectly, help me to continue

>Solution :

First of all, remember to check if the input length is less than 3 characters. Next, check the value of the 3rd element, then use String::replaceRange() to remove it. I’ve written a function process for you as a demo, as well as a few test cases to run it.

String process(String input) {
  if (input.length < 3) return input;
  if (input[2] != '0') return input;
  return input.replaceRange(2, 3, '');
}

void main() {
  print(process('12'));
  print(process('120'));
  print(process('123'));
  print(process('1204'));
  print(process('1200'));
  print(process('1200'));
  print(process('12001'));
}

Sample output:

12 12 123 124 120 120 1201

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading