Home > Mobile >  How to get the first two words in a string Flutter
How to get the first two words in a string Flutter

Time:04-06

I have this string example: Hello my name is

And this is what I want to show: Hello my

What is the best practice to do it?

Thanks in advance

CodePudding user response:

Split, then take(2) and then join them again:

  final src = 'Hello my name is';
  final result = src.split(' ').take(2).join(' ');
  print(result);

CodePudding user response:

The easiest way is to break down the sentence into a List of words :

String test = 'Hello my name is';

List<String> words = test.split(" ");
  
  
print('${words[0]} ${words[1]}');
  • Related