Question Details

No question body available.

Tags

dart

Answers (4)

June 15, 2025 Score: 0 Rep: 63 Quality: Low Completeness: 50%

The error you are encountering is because >= is used to compare 2 numbers. If you use it with a string, ofcourse there will be errors. To solve this, you need to convert each character in the string to an integer first. Use tryParse() for that. If the string is not a valid number it will give error. You can do it like this

    String name = 'saran7711@7';
    int length = name.length;
    int store = 0;

for (int i = 0; i < length; i++) { int? nameInt = int.tryParse(name[i]); if (nameInt == null) continue; // if the name us a string then skip it and move to next letter store = store + nameInt; }

print(store);
June 15, 2025 Score: 0 Rep: 16 Quality: Low Completeness: 80%

You cannot compare directly compare the element at index name[i] as this evaluates to a string and not a numerical value, your approach is trying to compare individual characters of a string (name[i]) using relational operators (>= and = 0 && name[i].compareTo('9')

June 17, 2025 Score: 0 Rep: 72,923 Quality: Low Completeness: 50%

You are treating name[i] as if it was a number, when it's a string.

Instead use codeUnitAt to extract the number:

const c0 = 0x30, c9 = 0x39; // Code units for 0 and 9 digits. String name = 'saran7711@7'; int store = 0; for (int i = 0; i < name.length; i++) { var char = name.codeUnitAt(i); if (char >= c0 && char
June 16, 2025 Score: -1 Rep: 1,966 Quality: Low Completeness: 80%

You can test this code in dartpad:

void main() {
  String name = 'saran7711@7';
  print(name); // saran7711@7

int length = name.length; int store = 0;

for (int i = 0; i < length; i++) { if (RegExp(r'[0-9]').hasMatch(name[i])) { store += int.parse(name[i]); } }

print(store); // 23 }

You can also use RegExp class with hasMatch abstract method to filter out a certain characters you want to extract (i.e., raw string from 0 to 9), and also by incorporating int parsing of the extracted numeric data before performing addition on it. The += (addition assignment operator) will work well for this, as it allows you to accumulate each new numeric value from name[i] with every iteration, until all available data has been processed.