Get First Character in String
To get first character in the given string in Dart, we can access the character in the string at index 0 using square bracket notation.
The syntax of expression to get the first character in the string myString
is
</>
Copy
myString[0]
Dart Program
In the following program, we take a string 'apple'
in variable myString
, and get the first character in this string.
main.dart
</>
Copy
void main() {
var myString = 'apple';
if (myString.length > 0) {
var output = myString[0];
print('First character : $output');
} else {
print('Empty string, please check.');
}
}
Output
First character : a
In the program, before accessing the character at index=0, we have checked if the string is not empty, so that when accessing the character we do not get any error.
Conclusion
In this Dart Tutorial, we learned how to get the first character in the given string in Dart.