如何根据用户输入计算文本字符串中的字数



我开始学习飞镖和长笛,但一个应用程序有问题。我正在尝试编写一个应用程序,统计用户输入的文本字符串中的单词数。我为此编写了countWords函数,但我不明白如何正确地向该函数发送文本字符串。有人能向我解释一下如何做到这一点并更正我的代码吗?

import 'package:flutter/material.dart';
import 'dart:convert';
class MyForm extends StatefulWidget {
@override
State<StatefulWidget> createState() => MyFormState();
}
class MyFormState extends State {
final _formKey = GlobalKey<FormState>();
final myController = TextEditingController();
int words_num = 0;
void countWords() {
var regExp = new RegExp(r"w+('w+)?");
int wordscount = regExp.allMatches(myController.text); //here I have trouble
setState(() {
words_num = wordscount;
});
}
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.all(10.0),
child: new Form(
key: _formKey,
child: new Column(
children: <Widget>[
new Text(
'Text string:',
style: TextStyle(fontSize: 20.0),
),
new TextFormField(
decoration:
InputDecoration(labelText: 'Enter your text string'),
controller: myController,
),
new SizedBox(height: 20.0),
new RaisedButton(
onPressed: () {
countWords();
},
child: Text('Count words'),
color: Colors.blue,
textColor: Colors.white,
),
new SizedBox(height: 20.0),
new Text(
'Number of words: $words_num',
style: TextStyle(fontSize: 20.0),
),
],
)));
}
}
void main() => runApp(new MaterialApp(
debugShowCheckedModeBanner: false,
home: new Scaffold(
appBar: new AppBar(title: new Text('Count words app')),
body: new MyForm())));

现在您正在将Iterable分配给int。由于需要长度,请使用Iterable类的length属性。

int wordscount = regExp.allMatches(myController.text).length;

这是假设你的正则表达式是工作的,在我看来它是工作的。如果它不是,那么你可以试试这个:

[w-]+

最新更新