简体   繁体   中英

Is there any method like char At in Dart?

String name = "Jack";  
char letter = name.charAt(0);    
System.out.println(letter);

You know this is a java method charAt that it gives you a character of a String just by telling the index of the String. I'm asking for a method like this in Dart, does Dart have a method like that?

You can use String.operator[] .

String name = "Jack";  
String letter = name[0];
print(letter);

Note that this operates on UTF-16 code units , not on Unicode code points nor on grapheme clusters. Also note that Dart does not have a char type, so you'll end up with another String .

If you need to operate on arbitrary Unicode strings, then you should use package:characters and do:

String name = "Jack";  
Characters letter = name.characters.characterAt(0);
print(letter);

Dart has two operations that match the Java behavior, because Java prints integers of the type char specially.

Dart has String.codeUnitAt , which does the same as Java's charAt : Returns an integer representing the UTF-16 code unit at that position in the string. If you print that in Dart, or add it to a StringBuffer , it's just an integer, so print("Jack".codeUnitAt(0)) prints 74 .

The other operations is String.operator[] , which returns a single-code-unit String . So print("Jack"[0]) prints J .

Both should be used very judiciously, since many Unicode characters are not just a single code unit. You can use String.runes to get code points or String.characters from package characters to get grapheme clusters (which is usually what you should be using, unless you happen to know text is ASCII only.)

You can use

String.substring(int startIndex, [ int endIndex ])

Example --

void main(){
   String s = "hello";
   print(s.substring(1, 2));
}

Output

e

Note that , endIndex is one greater than startIndex, and the char which is returned is present at startIndex.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM