首页 > 解决方案 > 如何从用户输入中计算文本字符串中的单词数

问题描述

我开始学习 Dart 和 Flutter 并且对一个应用程序有问题。我正在尝试编写一个应用程序来计算用户输入的文本字符串中的单词数。我为此编写了 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())));

标签: flutterdart

解决方案


现在你正在将一个分配Iterable给一个int。由于您想要长度,请使用classlength的属性。Iterable

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

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

[\w-]+

推荐阅读