Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find letter in a String (charAt)

Tags:

string

dart

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) {
    //..
  }
}    
like image 740
user2398664 Avatar asked May 05 '14 16:05

user2398664


3 Answers

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'
like image 142
Anthony Bobenrieth Avatar answered Oct 17 '22 13:10

Anthony Bobenrieth


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.

like image 7
Günter Zöchbauer Avatar answered Oct 17 '22 14:10

Günter Zöchbauer


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]);
like image 1
Giovanne Ramos Avatar answered Oct 17 '22 13:10

Giovanne Ramos