Home > Back-end >  Flutter How to find spesific word of string?
Flutter How to find spesific word of string?

Time:03-04

I have a TextField and controller. I am trying to find word inside this controller.

This is the text from TextField:

Hello people, from Mars

I tried this and this code returning how many word the controller has. So, it is 4.

    int mLength = controller1.text.split(' ').length;
    debugPrint(mLength.toString());

Then I tried the find last word with this code:

 debugPrint(controller1.text.split(" ").elementAt(isimLenght - 1));

But the problem has begin here. How do I know, how many word written by user? Maybe 4, maybe 10.. If I try to get first word or third word or seventh word, how do I get it? I tried to use for and for in but couldn't handle with these.

CodePudding user response:

So the issue is that you don't know the number of words in advance, but you still need to get some words at precise positions. You can do it this way:

var words = controller1.text.split(' ');
var fourthWord = ''; //assign here a default value, so you have the variable available later
var tenthWord = '';
//and so on, for each word in a precise position you need

if (words.length> 3){
   fourthWord = words[3];
}
if (words.length> 9){
   tenthWord = words[9];
}
//and so on...

//I suppose you need these words for something: in this way you have all of them set by default as empty 
processWords(fourthWord, tenthWord);

Another way is by using try...catch to get the errors, but the result is pretty much the same. Short example, instead of using if:

try{
  fourthWord=words[3];
} catch (e) {
  print('Not enough words');
}

}

CodePudding user response:

controller1.text is of String type which means all the methods from String class can be used to search a word, replace, find lenght etc.

controller1.text.split(' ') returns an array of Strings which means all the operations allowed on arrays or Lists are also by default possible here.

Search a specific word:

controller1.text.contains('from'); // Returns TRUE/FALSE
controller1.text.indexOf('from'); // Returns the start index

Get the count of words:

List<String> words = controller1.text.split(' ');
debugPrint(words[5]);

CodePudding user response:

You can get an array of words by:

var words = controller1.text.split(' ');

Iterating them:

for (var word in words) {
  print(word);
}

Pick one of them:

var picked = words[2];

How many words did the user input?

var count = words.length;
print('words: $count');

If you want to split the string by a space and the input contains no space at all, the result array will contain only 1 element - the whole string. But we could define a word without using a space separator. Maybe just an arbitrary string, try this example:


  void test() {
    var fullText = 'foobarfoofoobarbar';
    var searchFrom = 0;    
    var keyword = 'foo';
    var index = fullText.indexOf(keyword, searchFrom);  
    //will quit the loop if 'foo' cannot be found anymore  
    while (index != -1) {
      //first word 'foo' starts from index to index 3
      var firstFoo = fullText.substring(index, index   keyword.length);
      print('word $firstFoo: $index ${index   keyword.length}');
      
      //find next word 'foo' from index after the last one:
      searchFrom = index;
      index = fullText.indexOf('foo', searchFrom);
    }
    
  }

Didn't test it yet so no guaranteed it's working. But you could get the idea of searching inside a string.

CodePudding user response:

enter image description here

 var h = "Hello people, from Mars Hello==1 people1==, from1== Mars1==";
  var split = h.split(" ");
  printme(split, 0);
  printme(split, 1);
  printme(split, 2);
  printme(split, 3);
  printme(split, 4);
  printme(split, 5);
  printme(split, 6);
  printme(split, 7);
  printme(split, 8);
  printme(split, 9);
  printme(split, 10);

  printme(split, 11);
  printme(split, 12);
  printme(split, 100);
  printme(split, -1);
}

printme(split, int t) {
  var st = split.length - t.abs() > 0 ? split.elementAt(t.abs()) : "";
  print("$t=============>"   st);
  return st;
}

Output

0=============>Hello
1=============>people,
2=============>from
3=============>Mars
4=============>Hello==1
5=============>people1==,
6=============>from1==
7=============>Mars1==
8=============>
9=============>
10=============>
11=============>
12=============>
100=============>
-1=============>people,

Smaple Codedart pad code

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

TextEditingController   _textcontroller= new TextEditingController(
    text: "Hello people, from Mars Hello==1 people1==, from1== Mars1==");
TextEditingController _textlengthcontroller = new TextEditingController();
var text = "";

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter  ;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceAround,
          children: <Widget>[
            TextFormField(
              controller: _textcontroller,
            ),
            Container(
              height: 100,
              child: TextFormField(
                controller: _textlengthcontroller,
                keyboardType: TextInputType.number,
              ),
            ),
            Text(
              text,
            ),
            ElevatedButton(
                onPressed: () {
                  var s = printme(_textcontroller.text.split(" "),
                      int.parse(_textlengthcontroller.text));
                  setState(() {
                    text = s;
                  });
                },
                child: Text("Find My word"))
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

  printme(split, int t) {
    var st = split.length - t.abs() > 0
        ? split.elementAt(t.abs())
        : " ===============No WordFound=========";
    print("$t=============>"   st);
    return st;
  }
}
  • Related