I'm learning Dart now, and I was wondering how I can find letters in a String. I've tried to use charAt(), but then the Dart Editor says:

Class 'String' has no instance method 'charAt'.

So my question is: How can I find letters in a String in Dart?

For example, I want to find the "i" in the word "fire". How does this work without charAt()?

var items = "fire";

for (int i = 0; items.length; i++) {
  if (items.indexOf(items(charAt(i)) != -1) {
    //..
  }
}    
有帮助吗?

解决方案

As said in comments, you don't have to create your own function since indexOf / allMatches / contains are quiet enough for most of case.

And there is no charAt() equivalent since String act as a list of characters. You can use the [] operator to get a letter at a specific index:

'Hello World'[6] //return 'W'

其他提示

I think

items.indexOf('i');

print(items.indexOf('i')); // prints: 1 because 'i' is found on the 2nd position

is what you are looking for, but you already use it in your question.

Use the contains method!

Returns true if this string contains a match of [other]:

var string = 'Dart strings';
string.contains('D');                     // true
string.contains(new RegExp(r'[A-Z]'));    // true

If [startIndex] is provided, this method matches only at or after that index:

string.contains('X', 1);                  // false
string.contains(new RegExp(r'[A-Z]'), 1); // false

[startIndex] must not be negative or greater than [length].

bool contains(Pattern other, [int startIndex = 0]);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top