This short post shows you 2 ways to count the number of words in a given string.
1. Using split() method
We can use the split() method to return the list of the substrings between the white spaces in the given string.Advertisements
Example:
final String s = 'Kindacode.com is a website about programming.';
final List l = s.split(' ');
print(l.length);
Output:
6
2. Using Regular Expression
Using regular expression is a little bit more complicated but it gives you more flexibility.
AdvertisementsExample:
final String s =
'Kindacode.com is a website about programming. Under_score en-dash em-dash and some special words.';
final RegExp regExp = new RegExp(r"[w-._]+");
final Iterable matches = regExp.allMatches(s);
final int _count = matches.length;
print(_count);
Output:
13
Continue exploring more about Flutter and Dart:
- Displaying Subscripts and Superscripts in Flutter
- Flutter & Dart: Regular Expression Examples
- Sorting Lists in Dart and Flutter (5 Examples)
- Dart: Convert Map to Query String and vice versa
- Dart: Capitalize the First Letter of Each Word in a String
You can also check out our Flutter category page, or Dart category page for the latest tutorials and examples.