Home > database >  remove special index character from string | flutter
remove special index character from string | flutter

Time:01-07

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"

(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

CodePudding user response:

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

CodePudding user response:

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

}

  • Related